Emulator

Matrix product states

The module contains a light-weight MPS emulator.

class qtealeaves.emulator.mps_simulator.MPS(num_sites, convergence_parameters, local_dim=2, initialize='vacuum', requires_singvals=False, tensor_backend=None, sectors=None, **kwargs)[source]

Matrix product states class

Parameters

num_sites: int

Number of sites

convergence_parameters: TNConvergenceParameters

Class for handling convergence parameters. In particular, in the MPS simulator we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular

values are neglected, i.e. if \(\lamda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)

local_dim: int or list of ints, optional

Local dimension of the degrees of freedom. Default to 2. If a list is given, then it must have length num_sites.

initialize: str, optional

The method for the initialization. Default to “vacuum” Available: - “vacuum”, for the |000…0> state (no symmetric tensors yet) - “random”, for a random state at given bond dimension

requires_singvalsboolean, optional

Allows to enforce SVD to have singular values on each link available which might be useful for measurements, e.g., bond entropy (the alternative is traversing the whole TN again to get the bond entropy on each link with an SVD).

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

sectorsdict | None, optional

Can restrict symmetry sector and/or bond dimension in initialization. If empty, no restriction. The global symmetry sector is parsed from the the key global; intermediate sectors can be restricted via integer keys specifying the number of sites to the left of the corresponding link. Example: Restrict irreps after the second site at python-index=1, the key equals to 2 for two sites being on the left of the link. Default to None resulting in empty dictionary.

add_site(idx, state=None)[source]

Add a site in a product state in the link idx (idx=0 is before the first site, idx=N+1 is after the last). The state of the new index is |0> or the one provided.

Parameters

idxint

index of the link where you want to add the site

state: None or array-like

Vector state that you want to add

Details

To insert a new site in the MPS we first insert an identity on a link, then add a dimension-1 link to the identity and lastly contract the new link with the initial state, usually a |0>

apply_local_kraus_channel(kraus_ops)[source]

Apply local Kraus channels to tensor network. Does not work for MPS!

Parameters

kraus_opsdict of QTeaTensor

Dictionary, keys are site indices and elements the corresponding 3-leg kraus tensors

Returns

singvals_cut: float

Sum of singular values discarded due to truncation.

apply_mpo(mpo)[source]

Apply an MPO to the MPS on the sites sites. The MPO should have the following convention for the links: 0 is left link. 1 is physical link pointing downwards. 2 is phisical link pointing upwards. 3 is right link.

The sites are encoded inside the DenseMPO class.

Parameters

mpoDenseMPO

MPO to be applied

Returns

np.ndarray

Singular values cutted when the gate link is contracted

apply_nonlocal_two_site_operator(op, control, target, swap=False)[source]

Apply a non-local two-site operator, by taking first the SVD of the operator, contracting the almost-single-site operator to the respective sites and then propagating the operator to the correct site

Warning

The operations in this method are NOT ALWAYS well defined. If the left-operator tensor is not unitary, then we are applying a non-unitary operation to the state, and thus we will see a vanishing norm. Notice that, if the error can happen a warning message will be issued

Parameters

opnp.ndarray

Operator to be applied

controlint

control qubit index

targetint

target qubit index

swapbool, optional

If True, transpose the tensor legs such that the control and target are swapped. Default to False

Returns

np.ndarray

Singular values cutted when the gate link is contracted

apply_one_site_operator(op, pos)[source]

Applies a one operator op to the site pos of the MPS.

Parameters

op: QteaTensor of shape (local_dim, local_dim)

Matrix representation of the quantum gate

pos: int

Position of the qubit where to apply op.

apply_projective_operator(site, selected_output=None, remove=False)[source]

Apply a projective operator to the site site, and give the measurement as output. You can also decide to select a given output for the measurement, if the probability is non-zero. Finally, you have the possibility of removing the site after the measurement.

Warning

Applying projective measurements/removing sites is ALWAYS dangerous. The information of the projective measurement should be in principle carried over the entire mps, by iteratively applying SVDs across all sites. However, this procedure is highly suboptimal, since it is not always necessary and will be processed by the following two-sites operators. Thus, the procedure IS NOT applied here. Take care that entanglement measures through TNObsBondEntropy may give incorrect results right after a projective operator application. Furthermore, if working with parallel approaches, projective operators should be treated with even more caution, since they CANNOT be applied in parallel.

Parameters

site: int

Index of the site you want to measure

selected_output: int, optional

If provided, the selected state is measured. Throw an error if the probability of the state is 0

remove: bool, optional

If True, the measured index is traced away after the measurement. Default to False.

Returns

meas_state: int

Measured state

state_probfloat

Probability of measuring the output state

apply_two_site_operator(op, pos, swap=False, svd=True, parallel=False)[source]

Applies a two-site operator op to the site pos, pos+1 of the MPS.

Parameters

op: QteaTensor (local_dim, local_dim, local_dim, local_dim)

Matrix representation of the quantum gate

pos: int or list of ints

Position of the qubit where to apply op. If a list is passed, the two sites should be adjacent. The first index is assumed to be the control, and the second the target. The swap argument is overwritten if a list is passed.

swap: bool

If True swaps the operator. This means that instead of the first contraction in the following we get the second. It is written is a list of pos is passed.

svd: bool

If True, apply the usual contraction plus an SVD, otherwise use the QR approach explained in https://arxiv.org/pdf/2212.09782.pdf.

parallel: bool

If True, perform an approximation of the two-qubit gates faking the isometry center

Returns

singular_values_cutted: ndarray

Array of singular values cutted, normalized to the biggest singular value

Examples

swap=False  swap=True
  -P-M-       -P-M-
  2| |2       2| |2
  3| |4       4| |3
   GGG         GGG
  1| |2       2| |1
build_effective_operators(measurement_mode=False)[source]

Build the complete effective operator on each of the links. It assumes self.eff_op is set.

Parameters

measurement_modebool, optional

If True, enable measurement mode of effective operators

contract(other, boundaries=None)[source]

Contract the MPS with another MPS other <other|self>. By default it is a full contraction, but also a partial contraction is possible

Parameters

otherMPS

other MPS to contract with

boundariestuple of two ints, optional

Contract to MPSs from boundaries[0] to boundaries[1]. In this case the output will be a tensor of shape (chi_self, chi_other, 1) or (1, chi_self, chi_other). Default to None, which is full contraction

Returns

contractioncomplex | _AbstractQteaTensor

Result of the contraction

property current_max_bond_dim

Maximum bond dimension of the mps

property default_iso_pos

Returns default isometry center position, e.g., for initialization of effective operators.

default_sweep_order(skip_exact_rgtensors=False)[source]

Default sweep order to be used in the ground state search/time evolution. Default for MPS is left-to-right.

Arguments

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation. Usually set via the convergence parameters and then passed here. Default to False.

Returns

List[int]

The generator that you can sweep through

deprecated_get_eff_op_on_pos(pos)[source]

Obtain the list of effective operators adjacent to the position pos and the index where they should be contracted

Parameters

poslist

list of [layer, tensor in layer]

Returns

list of IndexedOperators

List of effective operators

list of ints

Indexes where the operators should be contracted

dot(other)[source]

Calculate the dot-product or overlap between two MPSs, i.e., <self | other>.

Parameters

otherMPS

Measure the overlap with this other MPS.

Returns ——-a

Scalar representing the overlap.

property first_non_orthogonal_left

First non orthogonal tensor starting from the left

property first_non_orthogonal_right

First non orthogonal tensor starting from the right

classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

Converts density matrix to MPS (not implemented yet).

classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]

Converts LPTN to MPS.

Parameters

lptn: LPTN

object to convert to MPS.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters. If None, the algorithm will try to extract conv_params from lptn.convergence_parameters. Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

mps: MPS

Decomposition of lptn.

classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Converts MPS to MPS.

Parameters

mps: MPS

object to convert to MPS.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

new_mps: MPS

Decomposition of mps, here a copy.

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Initialize the MPS tensors by decomposing a statevector into MPS form. All the degrees of freedom must have the same local dimension

Parameters

statevectorndarray of shape( local_dim^num_sites, )

Statevector describing the interested state for initializing the MPS

local_dimint, optional

Local dimension of the degrees of freedom. Default to 2.

conv_paramsTNConvergenceParameters, optional

Convergence parameters for the new MPS. If None, the maximum bond bond dimension possible is assumed, and a cut_ratio=1e-9. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Returns

objMPS

MPS simulator class

Examples

>>> -U1 - U2 - U3 - ... - UN-
>>>  |    |    |          |
# For d=2, N=7 and chi=5, the tensor network is as follows:
>>> -U1 -2- U2 -4- U3 -5- U4 -5- U5 -4- U6 -2- U7-
>>>  |      |      |      |      |      |      |
# where -x- denotes the bounds' dimension (all the "bottom-facing" indices
# are of dimension d=2). Thus, the shapes
# of the returned tensors are as follows:
>>>      U1         U2         U3         U4         U5         U6         U7
>>> [(1, 2, 2), (2, 2, 4), (4, 2, 5), (5, 2, 5), (5, 2, 4), (4, 2, 2), (2, 2, 1)]
classmethod from_tensor_list(tensor_list, conv_params=None, tensor_backend=None)[source]

Initialize the MPS tensors using a list of correctly shaped tensors

Parameters

tensor_listlist of ndarrays or cupy arrays or _AbstractQteaTensors

List of tensor for initializing the MPS

conv_paramsTNConvergenceParameters, optional

Convergence parameters for the new MPS. If None, the maximum bond bond dimension possible is assumed, and a cut_ratio=1e-9. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Returns

objMPS

The MPS class

classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]

Converts TTN to MPS.

Parameters

ttn: TTN

object to convert to MPS.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters. If None, the algorithm will try to extract conv_params from ttn.convergence_parameters. Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

mps: MPS

Decomposition of ttn.

classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Converts TTO to MPS.

Parameters

tto: TTO

Object to convert to MPS.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

mps: MPS

Decomposition of tto.

Returns two sets of sites forming the bipartition of the system for a loopless tensor network. The link is specified via two positions in the tensor network.

Arguments

pos_srctuple of two ints

Specifies the first tensor and source of the link.

pos_dsttuple of two ints

Specifies the second tensor and destination of the link.

Returns

sites_srclist of ints

Hilbert space indices when looking from the link towards source tensor and following the links therein.

sites_dstlist of ints

Hilbert space indices when looking from the link towards destination tensor and following the links therein.

List of tensor position where links are leading to.

Parameters

posint

Index of the tensor in the MPS

Returns

Tuple[int]

Index of the tensor connected through links to pos. None if they are open links.

Get the position of the partner tensor to use in the link expansion subroutine. It is the tensor towards the center, that is supposed to be more entangled w.r.t. the tensor towards the edge

Parameters

posint

Position w.r.t. which you want to compute the partner

Returns

int

Position of the partner

int

Link of pos pointing towards the partner

int

Link of the partner pointing towards pos

get_projector_function(pos, pos_links)[source]

Not implemented for MPS.

get_rho_i(idx)[source]

Get the reduced density matrix of the site at index idx

Parameters

idxint

Index of the site

Returns

_AbstractQteaTensor

Reduced density matrix of the site

get_substate(first_site, last_site, truncate=False)[source]

Returns the smaller MPS built of tensors from first_site to last_site.

Parameters

first_siteint

First site defining a range of tensors which will compose the new MPS. Python indexing assumed, i.e. counting starts from 0.

last_siteint

Last site of a range of tensors which will compose the new MPS. Python indexing assumed, i.e. counting starts from 0.

truncateBool

If False, the MPS tensors are returned as is - possibly with non-dummy links on edge tensors, i.e. a mixed state in MPS form. If True, the edges of MPS will be truncated to dummy links. Default to False.

Return

submps : MPS

get_tensor_of_site(idx)[source]

Generic function to retrieve the tensor for a specific site. Compatible across different tensor network geometries. This function does not shift the gauge center before returning the tensor.

Parameters

idxint

Return tensor containing the link of the local Hilbert space of the idx-th site.

property iso_center

Output the gauge center if it is well defined, otherwise None

iso_towards(new_iso, keep_singvals=False, trunc=False, conv_params=None, move_to_memory_device=True, normalize=False)[source]

Apply the gauge transformation to shift the isometry center to a specific site new_iso. The method might be different for other TN structure, but for the MPS it is the same.

Parameters

new_isoint

Position in the TN of the tensor which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD. If None, convergence parameters are taken from the TTN. Default to None.

move_to_memory_devicebool, optional

If True, when a mixed device is used, move the tensors that are not the isometry center back to the memory device. Default to True.

normalizebool, optional

Flag if intermediate steps should normalize. Default to False

Details

The tensors used in the computation will always be moved on the computational device. For example, the isometry movement keeps the isometry center end the effective operators around the center (if present) always on the computational device. If move_to_memory_device is False, then all the tensors (effective operators) on the path from the old iso to the new iso will be kept in the computational device. This is very useful when you iterate some protocol between two tensors, or in general when two tensors are involved.

isometrize_all()[source]

Isometrize towards the default isometry position with no previous isometry center, e.g., works as well on random states.

Returns

None

kron(other, inplace=False)[source]

Concatenate two MPS, taking the kronecker/outer product of the two states. The bond dimension assumed is the maximum between the two bond dimensions. The function doesn’t renormalize MPS.

Parameters

otherMPS

MPS to concatenate

inplacebool, optional

If True apply the kronecker product in place. Instead, if inplace=False give as output the product. Default to False.

Returns

MPS

Concatenation of the first MPS with the second in order

left_canonize(idx, trunc=False, keep_singvals=False, conv_params=None, move_to_memory_device=True, normalize=False)[source]

Isometrize from left to right, applying a gauge transformation to all bonds between 0 and idx. All sites between the first (leftmost one) and idx are set to (semi)-unitary tensors.

Parameters

idx: int

index of the tensor up to which the canonization occurs

trunc: bool, optional

If True, use the SVD instead of the QR for the canonization. It might be useful to reduce the bond dimension. Default to False.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the MPS. Default to None.

move_to_memory_devicebool, optional

If True, when a mixed device is used, move the tensors that are not the isometry center back to the memory device. Default to True.

normalizebool, optional

Flag if singular values should be normalized. Default to False

meas_bond_entropy()[source]

Measure the entanglement entropy along all the sites of the MPS using the Von Neumann entropy \(S_V\) defined as:

\[S_V = - \sum_i^{\chi} s^2 \ln( s^2)\]

with \(s\) the singular values

Return

measuresdict

Keys are the range of the bipartition from 0 to which the entanglement (value) is relative

meas_even_probabilities(threshold, qiskit_convention=False)[source]

Compute the probabilities of measuring a given state if it is greater than a threshold. The function goes down “evenly” on the probability tree. This means that there is the possibility that no state is returned, if their probability is lower then threshold. Furthermore, notice that the maximum number of states returned is :math:`(

rac{1}{threshold})`.

For a different way of computing the probability tree see the function meas_greedy_probabilities() or meas_unbiased_probabilities().

thresholdfloat

Discard all the probabilities lower then the threshold

qiskit_conventionbool, optional

If the sites during the measure are represented such that |201> has site 0 with value one (True, mimicks bits ordering) or with value 2 (False usually used in theoretical computations). Default to False.

probabilitiesdict

Dictionary where the keys are the states while the values their probabilities. The keys are separated by a comma if local_dim > 9.

meas_greedy_probabilities(max_prob, max_iter=None, qiskit_convention=False)[source]

Compute the probabilities of measuring a given state until the total probability measured is greater than the threshold max_prob. The function goes down “greedily” on the probability tree. This means that there is the possibility that a path that was most promising at the tree root will become very computationally demanding and not so informative once reached the leaves. Furthermore, notice that there is no maximum number of states returned, and so the function might be exponentially slow.

For a different way of computing the probability tree see the function meas_even_probabilities() or meas_unbiased_probabilities()

Parameters

max_probfloat

Compute states until you reach this probability

qiskit_conventionbool, optional

If the sites during the measure are represented such that |201> has site 0 with value one (True, mimicks bits ordering) or with value 2 (False usually used in theoretical computations). Default to False.

Return

probabilitiesdict

Dictionary where the keys are the states while the values their probabilities. The keys are separated by a comma if local_dim > 9.

meas_tensor_product(ops, idxs)[source]

Measure the tensor products of n operators ops acting on the indexes idxs. The operators should be MPOs, i.e. rank-4 tensors of shape (left, up, down, right). To retrieve the tensor product operators, left=right=1.

Parameters

opslist of ndarrays

List of numpy arrays which are one-site operators

idxslist of int

Indexes where the operators are applied

Returns

measurefloat

Result of the measurement

meas_weighted_sum(op_strings, idxs_strings, coefs)[source]

Measure the weighted sum of tensor product operators. See meas_tensor_product()

Parameters

op_stringslist of lists of ndarray

list of tensor product operators

idxs_stringslist of list of int

list of indexes of tensor product operators

coefslist of complex

list of the coefficients of the sum

Return

measurecomplex

Result of the measurement

ml_default_sweep_order(num_tensor_rule)[source]

Default sweep order for a machine learning optimization, where we replace the ground state sweep order.

Arguments

num_tensor_rule: int

Specify if it is a one-tensor or two-tensor update.

Returns

sweep_orderList

List of tensor positions compatible with the corresponding ansatz. For two-site rules, each pair is optimized once which skips one center position in respect to the ground state search for the two-tensor update.

ml_get_gradient_single_tensor(pos)[source]

Get the gradient w.r.t. to the tensor at pos similar to the two-tensor version.

Parameters

posint

Index of the tensor to work with.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

ml_get_gradient_two_tensors(pos, pos_p=None)[source]

Get the gradient w.r.t. the tensors at position pos, pos_p of the MPS following the procedure explained in https://arxiv.org/pdf/1605.05775.pdf for the data_sample given

Parameters

posint

Index of the tensor to optimize

pos_pint | None

Index of partner tensor. If None, partner tensor will be queried.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset, has_trivial_label_link=True, has_env_label_link=False)[source]

Generate an initial guess for a tensor network machine learning approach.

Arguments

convergence_parametersTNConvergenceParameters

Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.

tensor_backendTensorBackend

Selecting the tensor backend to run the simulations with.

initializestr

The string superposition-data will trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.

ml_data_mpoMLDataMPO

MPO of the labeled data set to be learned including the labels.

datasetList[MPS]

Data set represented as list of MPS states. Same order as in ml_data_mpo. Only accessed in case of superposition-data.

has_trivial_linkbool, optional

With a trivial link (True), the ML-MPS learns solely based on the overlap of the sample with the ansatz rounded to the closest integer. Instead, the typical ML approach with argmax over a vector is used with has_trivial_link=False. Default to True

has_env_label_linkbool, optional

Move label link into the environment, which means here having a non-trivial link towards the environment in the ansatz. Default to False.

Returns

ansatz_AbstractTN

Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.

ml_reorder_pos_pair(pos, pos_partner, link_pos, link_partner)[source]

MPS order is with left tensor first.

Arguments

posint | tuple[int]

Position of the first tensor in the network.

pos_partnerint | tuple[int]

Position of the partner tensor in the network.

link_posint

Link in tensor connecting to partner tensor.

link_partnerint

Link in partner tensor connecting to tensor.

Returns

pos, pos_partner, link_pos, link_partner

Re-ordering of tensor and partner tensor if beneficial.

ml_two_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with two tensors and the label link in the environment.

Parameters

posint | tuple(int)

Position of the tensor to be optimized in the network.

num_grad_stepsint

Number of steps as loop in the gradient descent.

Returns

lossfloat (as native data type of the backend on the CPU)

Value of the loss function.

modify_local_dim(value, idxs=None)[source]

Modify the local dimension of sites idxs to the value value. By default modify the local dimension of all the sites. If value is a vector then it must have the same length of idxs. Notice that there may be loss of information, it is up to the user to be sure no error is done in this procedure.

Parameters

valueint or array-like

New value of the local dimension. If an int, it is assumed it will be the same for all sites idxs, otherwise its length must be the same of idxs.

idxsint or array-like, optional

Indexes of the sites to modify. If None, all the sites are modified. Default to None.

classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]

Broadcast a whole tensor network.

Arguments

stateMPS (for MPI-rank root, otherwise None is acceptable)

State to be broadcasted via MPI.

commMPI communicator

Send state to this group of MPI processes.

tensor_backendTensorBackend

Needed to identity data types and tensor classes on receiving MPI threads (plus checks on sending MPI thread).

rootint, optional

MPI-rank of sending thread with the state. Default to 0.

static mpi_sample_n_unique_states(state, num_unique, comm, tensor_backend, cache_size=None, cache_clearing_strategy=None, filter_func=None, mpi_final_op=None, root=0, **kwargs)[source]

Try sampling a target number of unique states from TN ansatz.

mps_multiply_mps(other)[source]

Elementwise multiplication of the MPS with another MPS, resulting multiplying the coefficients of the statevector representation. If self represents the state a|000>+b|111> and other represent c|000>+d|111> then self.mps_multiply_mps(other)=ac|000>+bd|111>. It is very computationally demanding and the new bond dimension is the product of the two original bond dimensions.

Parameters

otherMPS

MPS to multiply

Returns

MPS

Summation of the first MPS with the second

norm()[source]

Returns the norm of the MPS as sqrt(<self|self>)

Return

norm: float

norm of the MPS

normalize()[source]

Normalize the MPS state, by dividing by \(\sqrt{<\psi|\psi>}\).

property physical_idxs

Physical indices property

classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]

Construct a product (separable) state in MPS form, given the local states of each of the sites.

Parameters

matList[np.array of rank 1] or np.array of rank 2

Matrix with ii-th row being a (normalized) local state of the ii-th site. Number of rows is therefore equal to the number of sites, and number of columns corresponds to the local dimension. Pass a list if different sites have different local dimensions so that they require arrays of different size.

paddingnp.array of length 2 or None, optional

Used to enable the growth of bond dimension in TDVP algorithms for MPS (necessary as well for two tensor updates). If not None, all the MPS tensors are padded such that the bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. If False, the bond dimensions are equal to 1. Default to None.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new MPS.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

MPS

Corresponding product state MPS.

classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]

Read an MPS via pickle or in the old formatted way shared with the Quantum TEA fortran modules.

Parameters

filename: str

PATH to the file

tensor_backendTensorBackend

Setup which tensor class to create.

cmplx: bool, optional

If True the MPS is complex, real otherwise. Default to True

order: str, optional

If ‘F’ the tensor is transformed from column-major to row-major, if ‘C’ it is left as read.

Returns

obj: py:class:MPS

MPS class read from file

Details

The formatted format looks like in the following:

Reads in column-major order but the output is in row-major. This is the only method that overrides the number of sites, since you may not know before reading.

reset(idxs=None)[source]

Reset the states of the sites idxs to the |0> state

Parameters

idxsint or list of ints, optional

indexes of the sites to reinitialize to 0. If default value is left all the sites are restarted.

right_canonize(idx, trunc=False, keep_singvals=False, conv_params=None, move_to_memory_device=True, normalize=False)[source]

Isometrize from right to left, applying a gauge transformation to all bonds between :py:method:`MPS.num_sites` and idx. All sites between the last (rightmost one) and idx are set to (semi)-unitary tensors.

Parameters

idx: int

index of the tensor up to which the canonization occurs

trunc: bool, optional

If True, use the SVD instead of the QR for the canonization. It might be useful to reduce the bond dimension. Default to False.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None.

move_to_memory_devicebool, optional

If True, when a mixed device is used, move the tensors that are not the isometry center back to the memory device. Default to True.

normalizebool, optional

Flag if intermediate steps should normalize. Default to False

sanity_check()[source]

A set of sanity checks helping for debugging which can be activated via the global variable RUN_SANITY_CHECK in this file.

Raises

QTeaLeavesError for any failing check.

Details

Runs checks on

  • Bond dimension between neighboring tensors.

  • Non-trivial local dimension

scale(factor)[source]

Scale the MPS state by a scalar constant using the gauge center.

Parameters

factorscalar

Factor is multiplied to the MPS at the gauge center.

scale_inverse(factor)[source]

Scale the MPS state by a scalar constant using the gauge center.

Parameters

factorscalar

Factor is multiplied to the MPS at the gauge center.

Update or set singvals on link via two positions.

property singvals

List of singular values in the bonds

site_canonize(idx, keep_singvals=False, normalize=False)[source]

Apply the gauge transformation to shift the isometry center to a specific site idx.

Parameters

idx: int

index of the tensor up to which the canonization occurs from the left and right side.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

normalizebool, optional

Flag if intermediate steps should normalize. Default to False

swap_qubits(sites, conv_params=None, trunc=True)[source]

This function applies a swap gate to sites in an MPS, i.e. swaps these two qubits

Parameters

sitesTuple[int]

The qubits on site sites[0] and sites[1] are swapped

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None.

Return

np.ndarray

Singualr values cut in the process of shifting the isometry center. None if moved through the QR.

property tensors

List of MPS tensors

to_dense(true_copy=False)[source]

Return MPS without symmetric tensors.

Parameters

true_copybool, optional

The function can be forced to return an actual copy with true_copy=True, while otherwise self can be returned if the MPS is already without symmetries. Default to False

Returns

dense_mpsMPS

MPS representation without symmetric tensors.

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Given a list of N tensors MPS [U1, U2, …, UN] , representing a Matrix Product State, perform the contraction in the Examples, leading to a single tensor of order N, representing a dense state.

The index ordering convention is from left-to-right. For instance, the “left” index of U2 is the first, the “bottom” one is the second, and the “right” one is the third.

Parameters

qiskit_order: bool, optional

weather to use qiskit ordering or the theoretical one. For example the state |011> has 0 in the first position for the theoretical ordering, while for qiskit ordering it is on the last position.

max_qubit_equivalent: int, optional

Maximum number of qubit sites the MPS can have and still be transformed into a statevector. If the number of sites is greater, it will throw an exception. Default to 20.

Returns

psindarray of shape (d ^ N, )

N-order tensor representing the dense state.

Examples

>>> U1 - U2 - ... - UN
>>>  |    |          |
to_tensor_list()[source]

Return the tensor list representation of the MPS. Required for compatibility with TTN emulator

Return

list

List of tensors of the MPS

to_ttn(trunc=False, convergence_parameters=None)[source]

Return a tree tensor network (TTN) representation as binary tree.

Details

The TTN is returned as a listed list where the tree layer with the local Hilbert space is the first list entry and the uppermost layer in the TTN is the last list entry. The first list will have num_sites / 2 entries. The uppermost list has two entries.

The order of the legs is always left-child, right-child, parent with the exception of the left top tensor. The left top tensor has an additional link, i.e., the symmetry selector; the order is left-child, right-child, parent, symmetry-selector.

Also see :py:func:ttn_simulator:`from_tensor_list`.

write(filename, cmplx=True)[source]

Write an MPS in python format into a FORTRAN format, i.e. transforms row-major into column-major

Parameters

filename: str

PATH to the file

cmplx: bool, optional

If True the MPS is complex, real otherwise. Default to True

Returns

None

Matrix Product State python simulator

The Matrix Product States (MPS) are an efficient way of representing a quantum state of 1-dimensional systems. The quantum system is represented as a tensor network, where each tensor represent a single degree of freedom of dimension local_dim. The entanglement of the system is encoded in the links between the tensors, and is bounded by the maximum bond dimension \(\chi\). The system is evolved by applying operators to the tensors, which are represented as tensors of dimension (local_dim x local_dim), if they are one-site operators (apply_one_site_operator()), or as tensors of dimension (local_dim x local_dim x local_dim x local_dim), if they are two-site operators (apply_two_site_operator()).

The entanglement constraint is imposed when we apply the two-site operators. Indeed, to come back to the MPS structure we apply a Singular Value Decomposition (SVD) and apply a truncation on the singular values. We truncate the singular values \(s=\{s_1, s_2, \dots, s_n\}\) with \(s_1\geq s_2\geq\dots\geq s_n\) such that:

\[\begin{split}\begin{cases} s_i \mbox{ is truncated if } & i>\chi \\ s_i \mbox{ is truncated if } & \frac{s_i}{s_1}\leq \epsilon \end{cases}\end{split}\]

where \(\epsilon\) is called cut ratio and is usually around \(\sim 10^{-9}\).

After the simulation we can perform the following measures: - Projective measurement of the system, which use a copy of the system and thus allow multiple measurements and keeping the state. Uses meas_projective(). - Measurement of local one-site operators along the full MPS, using meas_local(). - Measurements of tensor product operators, which are tensor product of single-site operators. Uses meas_tensor_product(). - Measurements of weighted sum of tensor product operators, using meas_weighted_sum(). - The bond entanglement entropy of the system along each bond, using meas_eantanglement(). This computation adds a minimum overhead, since it is already saved during the simulation and requires only a sum. For further informations on measuremens refer to Observables.

Example

Let us prepare an example to understand how to use the simulator. In this example we will use qubits, which means we fix the local dimension to 2. First, we need to decide the number of qubits we are interested in and the convergence parameters. We will only use 2 qubits and build a GHZ state. Remember that an MPS is always initialized in the Vacuum state \(|00\dots 0\rangle\), even though you can re-initialize it later on. (For further informations on the initialization see from_statevector(), from_tensor_list()).

Then, we have to evolve the state using one and two-site operators. In particular, we will use the Hadamard and Controlled NOT gates. We take the transposition of the gates to follow the notation of linear algebra, where the operators are applied to the left of the state, and so we can multiply the operators \(O_i\) as follows:

\[|\psi(t+1)\rangle = O_i |\psi(t)\rangle.\]

Lets write the code:

It is interesting to notice that we used a parameter called swap and set it to False. The apply_two_site_operator() method always applies the gates on position pos, pos+1. If the control qubit of the gate is on index pos then the swap parameter should be set to False, while if the control is in pos+1 it should be set to True. This function performs the swapping by permuting the tensor. After evolving the state, we can perform measuremnts or obtain the real statevector for debugging:

As expected, we got a measurement compatible with the state \(|GHZ\rangle=\frac{1}{\sqrt{2}}(|00\rangle+|11\rangle)\).

Finally, remember that you can access the tensors of the MPS class as you would access the elements of a list, or concatenate two mps using the :py:method:`kron` method.

List of overloaded operators

We report here a list of the overloaded operators and their actions, for an easy guide:

  • +, add two MPS states. If the first is in the state \(|00\rangle\) and the second in \(|11\rangle\), then their sum is \(|GHZ\rangle=\frac{1}{\sqrt{2}}(|00\rangle+|11\rangle)\)

  • +=, as before but acts in place

  • *, multiply the gauge/orthogonality center by a scalar number

  • *=, as before but acts in place

  • /, divide the gauge/orthogonality center by a scalar number

  • /=, as before but acts in place

  • @, contract two mps along all the open indexes. The left part is complex conjugate, which means a @ b is equivalent to \(\langle a | b \rangle\)

Tree tensor networks

class qtealeaves.emulator.TTN(num_sites, convergence_parameters, local_dim=2, requires_singvals=False, tensor_backend=None, network='binary', initialize='random', sectors=None, **kwargs)[source]

Tree tensor network class.

Parameters

num_sites: int

Number of sites

convergence_parameters: TNConvergenceParameters

Class for handling convergence parameters. In particular, in the TTN simulator we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular

values are neglected, i.e. if \(\lamda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)

local_dim: int, optional

Local dimension of the degrees of freedom. Default to 2.

requires_singvalsboolean, optional

Allows to enforce SVD to have singular values on each link available which might be useful for measurements, e.g., bond entropy (the alternative is traversing the whole TN again to get the bond entropy on each link with an SVD).

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

networkstr, optional

Default to “binary” (probably only option right now).

initialize: string, optional

Define the initialization method. For random entries use ‘random’, for empty TTN use ‘empty’. Default to ‘random’.

sectorsdict, optional

Can restrict symmetry sector and/or bond dimension in initialization. If empty, no restriction. Default to empty dictionary.

Details

The last layer contains the local Hilbert spaces and the most tensors.

apply_local_kraus_channel(kraus_ops)[source]

Apply local Kraus channels to tensor network. Does not work for TTN!

Parameters

kraus_opsdict of QTeaTensor

Dictionary, keys are site indices and elements the corresponding 3-leg kraus tensors

Returns

singvals_cut: float

Sum of singular values discarded due to truncation.

apply_mpo(mpo)[source]

Apply an MPO to the TTN on the sites sites. The MPO should have the following convention for the links: 0 is left link. 1 is physical link pointing downwards. 2 is phisical link pointing upwards. 3 is right link.

The sites are encoded inside the DenseMPO class.

Parameters

mpoDenseMPO

MPO to be applied

Returns

np.ndarray

Singular values cutted when the gate link is contracted

apply_one_site_operator(op, pos)[source]

Applies a one-site operator op to the physical site pos of the TTN.

Parameters

op: numpy array shape (local_dim, local_dim)

Matrix representation of the quantum gate

pos: int

Position of the qubit where to apply op.

apply_one_site_operator_weak_symmetry(op, pos)[source]

Applies a one-site operator op to the physical site pos of the TTN. This is the version for weak symmetries.

Parameters

op: _AbstractQteaTensor

Matrix representation of the quantum gate as rank-3 tensor where the third link is of dimension 1, but can carry a charge.

pos: int

Position of the qubit where to apply op.

apply_projective_operator(site, selected_output=None, remove=False)[source]

Apply a projective operator to the site site, and give the measurement as output. You can also decide to select a given output for the measurement, if the probability is non-zero. Finally, you have the possibility of removing the site after the measurement.

Warning

Applying projective measurements/removing sites is ALWAYS dangerous. The information of the projective measurement should be in principle carried over the entire TTN, by iteratively applying SVDs across all the networks. However, this procedure is highly suboptimal, since it is not always necessary and will be processed by the following two-sites operators. Thus, the procedure IS NOT applied here. Take care that entanglement measures through TNObsBondEntropy may give the None result. Furthermore, if working with parallel approaches, projective operators should be treated with even more caution, since they CANNOT be applied in parallel.

Parameters

site: int

Index of the site you want to measure

selected_output: int, optional

If provided, the selected state is measured. Throw an error if the probability of the state is 0

remove: bool, optional

If True, the measured index is traced away after the measurement. Default to False.

Returns

meas_state: int

Measured state

state_probfloat

Probability of measuring the output state

apply_two_site_operator(gate, sites, conv_params=None)[source]

Applies a two-site operator gate to the TTN on sites sites[0] and sites[1].

Parameters

gatenp array of shape (local_dim*local_dim, local_dim*local_dim)

Quantum gate to apply on a TTN. Note that links [2] and [3] of the gate are applied to the TTN.

siteslist/array of two ints

Left and right site on which to apply gate. The counting starts from 0.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None.

Return

np.ndarray

Singular values cut in the process of shifting the isometry center. None if moved through the QR.

assert_binary_tree()[source]

Assert for methods requiring binary trees.

build_effective_operators(measurement_mode=False)[source]

Build the complete effective operator on each of the links. Now assumes self.eff_op is set. Also builds effective projectors, self.eff_proj.

clear_cache(num_qubits_keep=None, all_probs=None, current_key=None)[source]

Internal cache for unbiased measurements can grow quickly. This function can erase either the whole cache (with num_qubits_keep == 0) or measurements from num_qubits_keep upwards.

Arguments

num_qubits_keepint or None, optional

Delete at least all cached entries for up to num_qubits_keep. num_qubits < num_qubits_keeped are deleted based on the cache limit. Higher number of qubits are less likely to be accessed by other measurements. Default to None (clear enough to meet cache limit if set)

current_keystr or None, optional

If we empty the cache by the strategy state, we need the current state as a (generalized) bitstring. Default to None (will fallback to num_qubit strategy)

all_probslist of dicts or None, optional

Contains already calculated branches of probability tree. If cache of TTN is deleted, corresponding entries of the all_probs have to be deleted as well, otherwise they use the “wrong” tensor in the TTN afterwards, i.e., wrong in terms of the direction of the isometrization. Default to None (potential side-effects, see details)

Details

There is a tricky part when using this for cleaning during a superiteration, where all_probs has to be delete up to the same number of qubits.

property current_max_bond_dim

Current maximum bond dimension of the TTN

property default_iso_pos

Returns default isometry center position, e.g., for initialization of effective operators.

default_isweep_order(skip_exact_rgtensors=False, back=False)[source]

Default sweep order for ground state search or time evolution. Bottom to top; left to right for even layers and viceversa for odd ones. Horizontal order is inverted when sweeping backwards.

Parameters

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation.

backBoolean, optional

Backwards sweep? False by default.

Returns

Iterator[Tuple[int]]

Iterator a sweep’s “(layer, tensor)” coordindates.

Details

The strategy for skipping exact RG tensors is the following. a) The full layer is skipped or all tensors in the layer are inside the sweep. (b) The top layer with its two tensors is always optimized and cannot be reduced to optimizing only one tensor.

default_sweep_order(skip_exact_rgtensors=False)[source]

Default sweep order forward. See default_isweep_order docstring. This returns an iterable rather than an iterator.

Parameters

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation. Usually set via the convergence parameters and then passed here. Default to False.

Returns

List[Tuple[int]]

List of sweep coordindates.

default_sweep_order_back(skip_exact_rgtensors=False)[source]

Default sweep order backwards. See default_isweep_order docstring. This returns an iterable rather than an iterator.

Parameters

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation. Usually set via the convergence parameters and then passed here. Default to False.

Returns

List[Tuple[int]]

List of sweep coordindates.

deprecated_get_eff_op_on_pos(pos)[source]

Obtain the list of effective operators adjacent to the position pos and the index where they should be contracted

Parameters

poslist

list of [layer, tensor in layer]

Returns

list of IndexedOperators

List of effective operators

list of ints

Indexes where the operators should be contracted

dot(other)[source]

Calculate the dot-product or overlap between two TTNs, i.e., <other | self>.

Parameters

otherTTN

Measure the overlap with this other TTN.

Returns

Scalar representing the overlap.

extend_local_hilbert_space(number_levels)[source]

Extend the local Hilbert by a certain number of levels without population. Extends the lowest layer with physical Hilbert space in the tree.

Parameters

number_levelsint

Defines the number of levels to be added. The levels are always appended to the end.

classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

Converts density matrix to TTN (not implemented yet)

classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]

Converts LPTN to TTN.

Parameters

lptn: LPTN

Object to convert to TTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

ttn: TTN

Decomposition of lptn.

classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Converts MPS to TTN.

Parameters

mps: MPS

object to convert to TTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

ttn: TTN

Decomposition of mps.

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Initialize the TTN by decomposing a statevector into TTN form.

Parameters

statevectorndarray of shape( [local_dim]*num_sites, )

Statevector describing the interested state for initializing the TTN

devicestr, optional

Device where the computation is done. Either “cpu” or “gpu”.

tensor_clstype for representing tensors.

Default to QteaTensor

classmethod from_tensor_list(tensor_list, singvals_list=None, tensor_backend=None, conv_params=None, local_dim=None)[source]

Construct a TTN from a listed list of tensors. The outer list contains the layers, the inner list contains the tensors within a layer.

The local Hilbert space is the first list entry and the uppermost layer in the TTN is the last list entry. The first list will have num_sites / 2 entries. The uppermost list has two entries.

The order of the legs is always left-child, right-child, parent with the exception of the left top tensor. The left top tensor has an additional link, i.e., the symmetry selector; the order is left-child, right-child, parent, symmetry-selector.

Also see mps_simulator.MPS.to_ttn().

classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]

Converts TTN to TTN.

Parameters

ttn: TTN

object to convert to TTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

ttn: TTN

Decomposition of ttn, here a copy.

classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Converts TTO to TTN.

Parameters

tto: TTO

Object to convert to TTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

ttn: TTN

Decomposition of tto.

Returns two sets of sites forming the bipartition of the system for a loopless tensor network. The link is specified via two positions in the tensor network.

Arguments

pos_srctuple of two ints

Specifies the first tensor and source of the link.

pos_dsttuple of two ints

Specifies the second tensor and destination of the link.

Returns

sites_srclist of ints

Hilbert space indices when looking from the link towards source tensor and following the links therein.

sites_dstlist of ints

Hilbert space indices when looking from the link towards destination tensor and following the links therein.

get_path(target, start=None)[source]

Calculates the path to a target, either starting at the isometry center or at a specified state.

Parameters

targetlist of two integers

Destination in terms of layer index and tensor index.

startNone or list of two integers, optional

Starting point for the path; if None, the isometry center is taken as the starting point. Default to None

Returns

List of lists with six entries … run # a QR on tensor path[*][1] in layer path[*][0] and r-link is # path[*][2]. Contract the r-tensor in tensor path[*][4] # in layer path[*][3] via link path[*][5].

Return a list of positions where all links are leading to. Number of entries is equal to number of links. Each entry contains the position as accessible in the actual tensor network.

Get the position of the partner tensor to use in the link expansion subroutine. In TTN, it is always the parent tensor.

Parameters

posTuple[int]

Position w.r.t. which you want to compute the partner

Returns

Tuple[int]

Position of the partner

int

Link of pos pointing towards the partner

int

Link of the partner pointing towards pos

get_projector_function(pos, pos_links)[source]

Generates a function which locally projects out the effective projectors. Used in the excited state search.

Arguments pos : tuple[int]

The position of the tensor from which to project.

pos_linkslist[tuple]

Position of neighboring tensors where the links in tensor lead to.

Returns Callable : the function.

get_quantum_mutual_information_matrix()[source]

Calculate the quantum mutual information for containing the quantum mutual information for every pair of qubits.

Returns

qmimnp.ndarray of rank-2

Quantum mutual information with one triangular matrix filled.

Details

Equation: implemented as S(rho(A)) + S(rho(B)) - S(rho(AB))

Efficiency: the underlying two-site density matrix could be optimized further.

get_rho_i(idx)[source]

Calculate the reduced density matrix for a single site. If the singular values are stored (i.e. not None) do not move the isometry center, but use them to compute local observables.

Parameters

idxinteger

Calculate the reduced density matrix of site idx. Recall python indices start at zero.

Returns

numpy ndarray : rank-2 tensor with the reduced density matrix.

get_rho_ij(ix, iy)[source]

Calculate the two-site reduced density matrix for one pair of sites.

Parameters

ixint

First site for the reduced density matrix.

iyint

Second site for the reduced density matrix, iy != ix.

Returns

rho_x_AbstractQteaTensor

Single-site reduced density matrix for site ix

rho_y_AbstractQteaTensor

Single-site reduced density matrix for site iy

rho_xy_AbstractQteaTensor

Two-site reduced density matrix for sites ix and iy.

get_substate(first_site, last_site, truncate=True)[source]

Returns the smaller TN built of tensors from the subtree. first_site and last_site (where sites refer to physical sites) define the subtree.

Parameters

first_siteint

First (physical) site defining a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

last_siteint

Last (physical) site of a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

truncateBool

If False, tensors are returned as is, i.e. TTO. If True, the edges of will be truncated to dummy links, i.e. TTN. Default to True. Default to False.

get_tensor_of_site(idx)[source]

Generic function to retrieve the tensor for a specific site. Compatible across different tensor network geometries.

Parameters

idxint

Return tensor containin the link of the local Hilbert space of the idx-th site.

get_unmasked_positions(layer_index)[source]

Returns a list of tensors which are not masked in the given layer. Not a list comprehension one-liner for readability.

is_masked_pos(pos)[source]

Whether the tensor at the given postion is physically irelevant and can be masked, as can happen when the number of physical sites is not a power of two.

iso_towards(new_iso, keep_singvals=False, trunc=False, conv_params=None, move_to_memory_device=True)[source]

Shift isometry center towards a certain tensor.

Parameters

new_isolist of two integers

New isometry center in terms of layer and tensor.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD. If None, convergence parameters are taken from the TTN. Default to None.

move_to_memory_devicebool, optional

If True, when a mixed device is used, move the tensors that are not the isometry center back to the memory device. Default to True.

Returns

singvals_cut_totnp.ndarray

Processed cut singular values in the process of shifting the isometry center. The processing depends on the truncation tracking mode. None if moved through the QR.

Details

We introduce an overhead if the TTN has no isometry center set up to now. This choice could be further optimized.

The tensors used in the computation will always be moved on the computational device. For example, the isometry movement keeps the isometry center end the effective operators around the center (if present) always on the computational device. If move_to_memory_device is False, then all the tensors (effective operators) on the path from the old iso to the new iso will be kept in the computational device. This is very useful when you iterate some protocol between two tensors, or in general when two tensors are involved.

isometrize_all()[source]

Isometrize towards [0, 0] with no assumption of previous isometry center, e.g., works as well on random states.

Returns

None

kron(other, inplace=False, fill_identity=False)[source]

Concatenate two TTN, taking the kronecker/outer product of the two states. The bond dimension assumed is the maximum between the two bond dimensions. For now, the restriction is that self and other must have the same number of layers. The function doesn’t renormalize TTN.

Parameters

otherTTN

TTN to concatenate

inplacebool, optional

If True apply the kronecker product in place. Instead, if inplace=False give as output the product. Default to False.

fill_identityBool

If True, uppermost layer tensors are simply set to identity tensors. Otherwise, constructs last layer by QR-ing the top tensors of self and other. Defatult to False.

Returns

TTN

Concatenation of the first TTN with the second.

leg_towards(pos, leg_start=None, leg_end=None, trunc=False, conv_params=None)[source]

The function shifts a selected leg from pos[0] to pos[1]. Remark: the set isometry center is automatically shifted throughout procedure. However, this isometry center corresponds to the real isometry center only when the shifting leg is not extra, i.e. does not come from contracting the 2-qubit gate. Nevertheless, when the applying the 2-qubit gate, the final position tensor will become the real isometry center outside this function, after contracting the gate to the second site.

Parameters

pos2x2 array

pos[0,:] indicates the position of the starting tensor, and pos[1,:] indicates the position of the destination tensor, such that pos[ii,:] = [layer_index, tensor_index].

leg_startNone or int

Use only if you want to shift one of the physical links to another physical site. Tells on which position in a tensor is a leg we want to shift. If None, it is assumed that the shifting leg is on the last axis. Note that counting starts from zero. Default to None.

leg_endNone or int

Use only if you want to shift one of the physical links to another physical site. Tells on which position in a destination tensor we want the extra leg to be. If None, a shifted leg is assumed to be put on the last axis. Default to None.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD. If None, convergence parameters are taken from the TTN. Default to None.

Return

np.ndarray

Processed cut singular values in the process of shifting the isometry center. The processing depends on the truncation tracking mode. Array of None if moved through the QR.

meas_bond_entropy()[source]

Measure the entanglement entropy along the bipartitions of the tree using the Von Neumann entropy \(S_V\) defined as:

\[S_V = - \sum_i^{\chi} s^2 \ln( s^2)\]

with \(s\) the singular values

Return

measuresdict

Keys are the range of the smallest bipartition to which the entanglement (value) is relative

meas_tensor_product(ops, idxs)[source]

Measure the tensor products of n operators ops acting on the indexes idxs

Parameters

opslist of ndarrays

List of numpy arrays which are one-site operators

idxslist of int

Indexes where the operators are applied

Returns

measurefloat

Result of the measurement

meas_weighted_sum(op_strings, idxs_strings, coefs)[source]

Measure the weighted sum of tensor product operators. See meas_tensor_product()

Parameters

op_stringslist of lists of ndarray

list of tensor product operators

idxs_stringslist of list of int

list of indexes of tensor product operators

coefslist of complex

list of the coefficients of the sum

Return

measurecomplex

Result of the measurement

ml_get_gradient_single_tensor(pos)[source]

Get the gradient w.r.t. to the tensor at pos similar to the two-tensor version.

Parameters

posint

Index of the tensor to work with.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

ml_get_gradient_two_tensors(pos, pos_p=None)[source]

Get the gradient w.r.t. the tensors at position pos, pos_p of the MPS following the procedure explained in https://arxiv.org/pdf/1605.05775.pdf for the data_sample given

Parameters

posint

Index of the tensor to optimize

pos_pint | None

Index of partner tensor. If None, partner tensor will be queried.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset)[source]

Generate an initial guess for a tensor network machine learning approach.

Arguments

convergence_parametersTNConvergenceParameters

Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.

tensor_backendTensorBackend

Selecting the tensor backend to run the simulations with.

initializestr

The string superposition-data will trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.

ml_data_mpoMLDataMPO

MPO of the labeled data set to be learned including the labels.

datasetList[MPS]

Data set represented as list of MPS states. Same order as in ml_data_mpo.

Returns

ansatz_AbstractTN

Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.

ml_two_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with two tensors and the label link in the environment.

classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]

Broadcast a whole tensor network.

Arguments

stateTTN (for MPI-rank root, otherwise None is acceptable)

State to be broadcasted via MPI.

commMPI communicator

Send state to this group of MPI processes.

tensor_backendTensorBackend

Needed to identity data types and tensor classes on receiving MPI threads (plus checks on sending MPI thread).

rootint, optional

MPI-rank of sending thread with the state. Default to 0.

static mpi_sample_n_unique_states(state, num_unique, comm, tensor_backend, cache_size=None, cache_clearing_strategy=None, filter_func=None, mpi_final_op=None, root=0, **kwargs)[source]

Try sampling a target number of unique states from TN ansatz.

norm()[source]

Return the norm of a TTN sqrt(<psi|psi>). Different from tensors.norm() by sqrt!

permute_spo_for_two_tensors(spo_list, theta, link_partner)[source]

Incoming order Ta, Tb, Pa, Pb

plot(fig, axis, link_quantity=None, plot_tensors=False, noticks=True, colormap='jet', cmap_label=None)[source]

Plot the TTN in a matplotlib figure on a specific axis. The plot is a TTN, with links and tensors. The physical links are not represented. The color of the links is encoding the link_quantity value. For example, if the link quantity is the entanglement, the color of the link will encode the entanglement of that link. You can pass some quantity that will be represented as a colorcode on the link.

TODO: add color code for quantities for the tensors too.

Parameters

figmatplotlib Figure

The figure where to plot

axismatplotlib axis

The axis where to plot

link_quantitynp.ndarray, optional

Colorcode of the link through np.ndarray of double, by default None. If None, black is used

plot_tensorsbool, optional

If True, plot tensors as white dots with black edge, by default False

noticksbool, optional

If True, remove the ticks from the axis, by default True

colormapstr, optional

Colormap to use, by default “jet”

cmap_label: str, optional

Label of the colormap, by default None.

Returns

None

Acts in place on the figure/axis

pre_timeevo_checks(raise_error=False)[source]

Check if a TN ansatz is ready for time evolution.

print_tensor_shapes(how_many_layers=None, how_many=None)[source]

Prints the shape of tensors in TTO, layer by layer.

Parameters

how_many_layersint, optional

Only the shapes of tensors from the first <how_many_layers> layers are printed if how_many_layers = None, shapes of all of the tensors are printed. Default is None.

how_many: int, array-like of ints, optional

Only the first <how_many> tensors of the layer are printed. If None, all the tensors are printed. If int, this number of tensor are printed for each layer. If array-like, you can individually select the number of tensors to be printed. By default None.

Return

None

print_tensors(how_many_layers=None, how_many=None)[source]

Prints the tensors in TTO layer by layer, together with their shape.

Parameters

how_many_layersint, optional

Only the tensors from the first <how_many_layers> layers are printed. If how_many_layers = None, all tensors from all layers are printed. Default is None.

how_many: int, array-like of ints, optional

Only the first <how_many> tensors of the layer are printed. If None, all the tensors are printed. If int, this number of tensor are printed for each layer. If array-like, you can individually select the number of tensors to be printed. By default None.

Return

None

classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]

Construct a product (separable) state in TTN form, given the local states of each of the sites.

Parameters

matList[np.array of rank 1] or np.array of rank 2

Matrix with ii-th row being a (normalized) local state of the ii-th site. Number of rows is therefore equal to the number of sites, and number of columns corresponds to the local dimension. Pass a list if different sites have different local dimensions so that they require arrays of different size.

paddinglist of length 2 or None, optional

Used to enable the growth of bond dimension in TDVP algorithms for TTN (necessary as well for two tensor updates). If not None, all the TTN tensors are padded such that the bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. If False, the bond dimensions are equal to 1. Default to None.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new TTN.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

prod_ttnTTN

Corresponding product state TTN.

classmethod product_state_from_local_states_2d(mat_2d, padding=None, mapping='HilbertCurveMap', return_map=False, convergence_parameters=None, tensor_backend=None)[source]

Construct a product (separable) state in 1d TTN form for a 2d system by mapping it to 1d, given the local states of each of the sites.

Parameters

mat_2dnp.array of rank 2

Array with third axis being a (normalized) local state of the (ii,jj)-th site (where ii and jj are indices of the first and second axes). Product of first two axes’ dimensions is therefore equal to the total number of sites, and third axis dimension corresponds to the local dimension.

paddingnp.array of length 2 or None, optional

Used to enable the growth of bond dimension in TDVP algorithms for TTN (necessary as well for two tensor updates). If not None, all the TTN tensors are padded such that the bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. If False, the bond dimensions are equal to 1. Default to None.

mappingstring or instance of HilbertCurveMap,

optional

Which 2d to 1d mapping to use. Possible inputs are: ‘HilbertCurveMap’, ‘SnakeMap’, and ‘ZigZagMap’. Default is ‘HilbertCurveMap’.

return_mapboolean, optional

If True, the function returns array map with indices of 2d to 1d mapping. Default to False.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new TTN.

Return

prod_ttnTTN

Corresponding product state TTN.

mapnp.array, returned only if return_map==True

Nx2 Matrix, where N is a total number of particles. The values in the ii-th row of the matrix denote particle’s position in a corresponding 2d grid.

classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]

Read an TTN via pickle or in the old formatted way shared with the Quantum TEA fortran modules.

Parameters

filename: str

PATH to the file

tensor_backendTensorBackend

Setup which tensor class to create.

cmplx: bool, optional

If True the MPS is complex, real otherwise. Default to True

order: str, optional

Format in which the tensors are saved. If ‘F’ column-major, if ‘C’ row major”

Returns

obj: py:class:TTN

TTN class read from file

Details

The formatted format looks like in the following:

Reads in column-major order but the output is in row-major. This is the only method that overrides the number of sites, since you may not know before reading.

Many fields stored in a TTN for the fortran code are not kept as they can be easily retrieved on the python side.

The performance can be improved if we consider converting the isometry center in fortran to python and ensure a conversion is always possible.

classmethod read_v0_2_29(filename, tensor_backend, cmplx=True, order='F')[source]

Read a TTN written by FORTRAN in a formatted way on file. Reads in column-major order but the output is in row-major. This is the only method that overrides the number of sites, since you may not know before reading.

Parameters

filename: str

PATH to the file

tensor_backendTensorBackend

Setup which tensor class to create.

cmplx: bool, optional

If True the MPS is complex, real otherwise. Default to True

order: str, optional

Format in which the tensors are saved. If ‘F’ column-major, if ‘C’ row major”

Returns

obj: py:class:TTN

TTN class read from file

Details

Many fields stored in a TTN for the fortran code are not kept as they can be easily retrieved on the python side.

The performance can be improved if we consider converting the isometry center in fortran to python and ensure a conversion is always possible.

sandwich(other)[source]

In the case of pure state TTN, calculate the dot-product, i.e. <other | self>.

Parameters

otherTTN

Measure the overlap with this other TTN.

Returns

Scalar representing the overlap.

sanity_check()[source]

Executing a series of default checks on TTN for debugging purposes. The execution is controlled by the module variable RUN_SANITY_CHECKS and allows a fast return if RUN_SANITY_CHECKS == False.

Details

The current checks include:

  • normalization

scale(factor)[source]

Scale a TTN with a scalar factor.

scale_inverse(factor)[source]

Scale a TTN with a scalar factor.

set_cache_clearing_strategy_sampling(strategy)[source]

Set strategy for clearing cache

Arguments

strategystr

Strategy to be applied, either num_qubits or state.

set_cache_limit_sampling(cache_limit_bytes)[source]

Set a cache limit in bytes for the sampling procedure.

Arguments

cache_limit_bytesint

Size of the cache for sampling in bytes.

set_sanity_check(status)[source]

Set execution of sanity checks for TTN module.

Arguments

statusbool

If True, sanity checks will run.

Update or set singvals on link via two positions.

shift_iso_to(source_tens, target_tens, source_link, target_link, trunc=False, conv_params=None)[source]

Shift isometry from source tensor to target tensor.

Parameters

source_tensnp.ndarray

Run QR decomposition over one link of this tensor

target_tensnp.ndarray

Contract R-matrix from QR into this tensor.

source_linkint

Run QR over this link source_link

target_linkint

Contract R-matrix via this link target_link into the target tensor.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD. If None, convergence parameters are taken from the TTN. If isometry shifting is performed via QR, conv_params is set to None automatically. Default to None.

Returns

qtensnp.ndarray

New gauged tensor taking the place of source_tens

t_tensnp.ndarray

New gauge center taking the place of target_tens

singvals_cutnp.ndarray

Singular values cut in moving the iso. If the iso is moved through the QR then it is None.

shift_leg_to(source_tens, target_tens, source_link, target_link, trunc=False, conv_params=None)[source]

Shift a last leg from source tensor to target tensor by running a QR decomposition on source_tens and contracting R matrix with target_tens. If the shifting leg is not extra, i.e. does not come from contracting the 2-qubit gate, the procedure shifts the isometry center of the TTN.

Parameters

source_tensnp.ndarray

A tensor from which the leg is shifted. It is assumed that the leg to be shifted is on the last axis of this tensor. Run QR decomposition over one link of this tensor.

target_tensnp.ndarray

A tensor to which the leg is shifted. Contract R-matrix from QR into this tensor.

source_linkint

Run QR over the link source_link and last leg.

target_linkint

Contract R-matrix via the link target_link into the target tensor.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None. If leg shifting is performed via QR, conv_params is set to None automatically. Default to None.

Return

q_tensnp.ndarray

New tensor taking the place of source_tens

t_tensnp.ndarray

New tensor taking the place of target_tens. If the shifting leg is not an extra leg, i.e. does not come from previously contracting the 2-qubit gate,`target_tens` represents a new iso center.

singvals_cutfloat or None

Singular values cut (if trunc=True) or None

site_canonize(idx, keep_singvals=False)[source]

Shift the isometry center to the tensor containing the corresponding site.

Parameters

idxint

Index of the physical site which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

classmethod sum_approximate(sum_states, sum_amplitudes=None, convergence_parameters=None, initial_state=None, max_iterations=10, dif_goal=1e-16, normalize_result=True)[source]

Computes the optimal TTN representation of the sum a_i psi_i for a set of TTN psi_i and ampltudes a_i. Uses the TTNProjectors to optimize the sum.

Arguments sum_states : list[TTN]

List of TTNs to sum.

sum_amplitudeslist[float] | None

List of amplitudes for each summand. If None, all are set to 1.

convergence_parametersTNConvergenceParameters

The convergence parameters for the resulting state. If None, a default convergence parameters object is created.

initial_stateTTN | None

The initial state for the optimization. If None will start with a random state.

max_iterationsint

The maximal number of iterations to optimize the sum.

dif_goalfloat

The convergence is gauged by computing |<psi|psi_i> - a_i|. We stop if this is smaller than dif_goal for all i.

normalize_resultbool

Whether to normalize the result.

Returns TTN : A TTN approximation of the sum.

swap_qubits(sites, conv_params=None, trunc=True)[source]

This function applies a swap gate to sites in a TTN, i.e. swaps these two qubits.

Parameters

siteslist/array of two int

The qubits on sites sites[0] and sites[1] are swapped.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None.

trunc: bool, optional

If True, move through SVDs, otherwise through QRs. Default to True.

Return

np.ndarray

Singualr values cut in the process of shifting the isometry center. None if moved through the QR.

to_dense(true_copy=False)[source]

Return TTN without symmetric tensors.

to_mps_tensor_list(conv_params=None)[source]

Map a binary TTN to a 1-layer tensor list that can be used to initialize an MPS with :py:function:`MPS.from_tensor_list(tensor_list)`.

At each iteration the algorithm performs the operations highlighted in the codeblock below.

  o-------o           o---o---o---o
 / \     / \  ====>   |   |   |   | ====>  o---o---o---o
o   o   o   o         o   o   o   o       / \ / \ / \ / \

Parameters

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use in the procedure. If None is given, then use the default convergence parameters of the TTN. Default to None.

Returns

list of numpy ndarray

Tensors that will constitute the MPS

numpy ndarray

Singular values cut in the procedure

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Decompose a given TTN into statevector form.

Parameters

qiskit_orderbool, optional

If true, the order is right-to-left. Otherwise left-to-right (which is the usual order in physics). Default to False.

max_qubit_equivalentint, optional

Maximum number of qubits for which the statevector is computed. i.e. for a maximum hilbert space of 2**max_qubit_equivalent. Default to 20.

Returns

psiinstance of _AbstractQteaTensor

The statevector of the system

to_tensor_list()[source]

Return the tensors in the TTN as a nested list

Returns

list of lists numpy ndarray

Tensors that will constitute the TTN

unset_all_singvals()[source]

Unset all the singvals in the TTN due to a local operation that is modifying the global state and the entanglement structure, such as a projective measurement.

Returns

None

write(filename, cmplx=True)[source]

Write the TTN into a FORTRAN compatible file.

Parameters

filename: str

Path to the file. Folders in the path must exists and are not created on-the-fly.

cmplx: bool, optional

If True the TTN is complex, real otherwise. Default to True

Returns

None

Locally purified tensor networks

class qtealeaves.emulator.LPTN(num_sites, conv_params, local_dim=2, tensor_backend=None, iso_center=None, initialize='vacuum', **kwargs)[source]

LOCALLY PURIFIED TENSOR NETWORK CLASS - operator order of legs: 0 - left bond, 1 - lower (physical) leg, 2 - upper leg, 3 - right bond

Parameters

num_sitesint

Number of sites

conv_paramsTNConvergenceParameters

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) /\(\lambda_max\) <= \(\epsilon\) are truncated

local_dimint, optional

Dimension of Hilbert space of single site (defined as the same for each site). Default is 2

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

initializestr

How to initialize the LPTN. Options are ‘vacuum’ or ‘pure_random’. Default to ‘vacuum’.

iso_centerNone or list of two ints, optional

Isometry center is between the two sites specified in a list. The counting starts at 1. If the LPTN has no isometry center, iso_center = None. Default is None

initializestr, optional

Available options are vacuum, pure_random (pure state, but random), and infinite_t. Default to vacuum

Initialization

|000...000><000---000|

Tensor representation

|   |   |   |   |
--O---O---O---O---O--

} –> complex conjugates of tensors below, | | | | | access with LPTN.cc_tensors

--O---O---O---O---O--

} –> these are contained in LPTN.tensors | | | | |

Attributes

LPTN.num_sitesint

Number of sites

LPTN.local_dimint

Local Hilbert space dimension

LPTN.tensorslist

Values of tensors in LPTN

LPTN.cc_tensorslist

Values of tensors in complex conjugate part of LPTN

LPTN._max_bond_dimint

Maximal bond dimension

LPTN._cut_ratiofloat

Cut ratio

LPTN.iso_centerNone or list of int, optional

Isometry center is between the two sites specified in a list. The counting starts at 1. If the LPTN has no isometry center, iso_center = None.

apply_projective_operator(site, selected_output=None, remove=False)[source]

Apply a projective operator to the site site, and give the measurement as output. You can also decide to select a given output for the measurement, if the probability is non-zero. Finally, you have the possibility of removing the site after the measurement.

Warning

Applying projective measurements/removing sites is ALWAYS dangerous. The information of the projective measurement should be in principle carried over the entire mps, by iteratively applying SVDs across all sites. However, this procedure is highly suboptimal, since it is not always necessary and will be processed by the following two-sites operators. Thus, the procedure IS NOT applied here. Take care that entanglement measures through TNObsBondEntropy may give incorrect results right after a projective operator application. Furthermore, if working with parallel approaches, projective operators should be treated with even more caution, since they CANNOT be applied in parallel.

Parameters

site: int

Index of the site you want to measure

selected_output: int, optional

If provided, the selected state is measured. Throw an error if the probability of the state is 0

remove: bool, optional

If True, the measured index is traced away after the measurement. Default to False.

Returns

meas_state: int

Measured state

state_probfloat

Probability of measuring the output state

build_effective_operators(measurement_mode=False)[source]

Build the complete effective operator on each of the links. Now assumes self.eff_op is set.

Parameters

measurement_modebool, optional

If True, enable measurement mode of effective operators

property cc_tensors

complex conjugate part of LPTN, returns complex conjugate tensors

property default_iso_pos

Returns default isometry center position, e.g., for initialization of effective operators.

classmethod dm_to_lptn(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

For a given density matrix in matrix form returns LPTN form

Parameters

rhondarray

Density matrix

n_sitesint

Number of sites

dimint

Local Hilbert space dimension

conv_paramsTNConvergenceParameters

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) /\(\lambda_max\) <= \(\epsilon\) are truncated

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

probBoolean, optional

If True, returns eigenvalues of initial eigenvalue decomposition. If everything is correct, should correspond to mixed state probabilities

Return

rho_lptn:py:class::LPTN

Density matrix in LPTN form

(if prob==True) : val : 1D np.ndarray

Eigenvalues of initial EVD = mixed state probabilities

classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

For a given density matrix in matrix form returns LPTN form

Parameters

rhondarray

Density matrix

n_sitesint

Number of sites

dimint

Local Hilbert space dimension

conv_paramsTNConvergenceParameters

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) /\(\lambda_max\) <= \(\epsilon\) are truncated

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

probBoolean, optional

If True, returns eigenvalues of initial eigenvalue decomposition. If everything is correct, should correspond to mixed state probabilities

Return

rho_lptn:py:class::LPTN

Density matrix in LPTN form

(if prob==True) : val : 1D np.ndarray

Eigenvalues of initial EVD = mixed state probabilities

classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]

Converts LPTN to LPTN.

Parameters

lptn: LPTN

object to convert to LPTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

new_lptn: LPTN

Decomposition of lptn.

classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Converts MPS to LPTN.

Parameters

mps: MPS

object to convert to LPTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters. If None, the algorithm will try to extract conv_params from mps.convergence_parameters. Default to None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

lptn: LPTN

Decomposition of mps.

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Decompose statevector to tensor network.

classmethod from_tensor_list_mps(tensor_list, conv_params=None, iso_center=None)[source]

Initialize the LPTN tensors using a list of MPS shaped tensors. A dummy leg is added and then the function from_tensor_list is called.

Parameters

tensor_listlist of ndarrays

List of tensors for initializing the LPTN

conv_paramsTNConvergenceParameters, optional

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) / \(\lambda_max\) <= \(\epsilon\) are truncated

iso_centerNone or list of int, optional

Isometry center is between the two sites specified in a list. If the LPTN has no isometry center, iso_center = None. Default is None

Return

objLPTN

The LPTN class composed of the given tensors


classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]

Converts TTN to LPTN.

Parameters

ttn: TTN

object to convert to LPTN.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters. If None, the algorithm will try to extract conv_params from ttn.convergence_parameters. Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

lptn: LPTN

Decomposition of ttn.

classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Converts TTO to LPTN.

Parameters

tto: TTO

object to convert to LPTN.

conv_params: TNConvergenceParameters

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

lptn: LPTN

Decomposition of tto.

List of tensor position where links are leading to.

Parameters

posint

Index of the tensor in the MPS

Returns

Tuple[int]

Index of the tensor connected through links to pos. None if they are open links.

get_rho_i(idx)[source]

Calculate the reduced density matrix for a single site.

Parameters

idxinteger

Calculate the reduced density matrix of site idx. Recall python indices start at zero.

Returns

2D np.ndarray :

Reduced density matrix.

get_rho_ij(idx)[source]

Calculate the reduced density matrix for two neighbour sites.

Parameters

idxinteger

Calculate the reduced density matrix of sites idx and ``idx``+1. Recall python indices start at zero.

Returns

2D np.ndarray :

Reduced density matrix.

ml_get_gradient_single_tensor(pos)[source]

Get the gradient w.r.t. to the tensor at pos similar to the two-tensor version.

Parameters

posint

Index of the tensor to work with.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

ml_get_gradient_two_tensors(pos, pos_p=None)[source]

Get the gradient w.r.t. the tensors at position pos, pos_p of the MPS following the procedure explained in https://arxiv.org/pdf/1605.05775.pdf for the data_sample given

Parameters

posint

Index of the tensor to optimize

pos_pint | None

Index of partner tensor. If None, partner tensor will be queried.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset)[source]

Generate an initial guess for a tensor network machine learning approach.

Arguments

convergence_parametersTNConvergenceParameters

Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.

tensor_backendTensorBackend

Selecting the tensor backend to run the simulations with.

initializestr

The string superposition-data will trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.

ml_data_mpoMLDataMPO

MPO of the labeled data set to be learned including the labels.

datasetList[MPS]

Data set represented as list of MPS states. Same order as in ml_data_mpo.

Returns

ansatz_AbstractTN

Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.

ml_two_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with two tensors and the label link in the environment.

classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]

Broadcast a whole tensor network.

Arguments

stateLPTN (for MPI-rank root, otherwise None is acceptable)

State to be broadcasted via MPI.

commMPI communicator

Send state to this group of MPI processes.

tensor_backendTensorBackend

Needed to identity data types and tensor classes on receiving MPI threads (plus checks on sending MPI thread).

rootint, optional

MPI-rank of sending thread with the state. Default to 0.

static mpi_sample_n_unique_states(state, num_unique, comm, tensor_backend, cache_size=None, cache_clearing_strategy=None, filter_func=None, mpi_final_op=None, root=0, **kwargs)[source]

Try sampling a target number of unique states from TN ansatz.

norm()[source]

Calculate the norm of the state, where the state is X of rho = X Xdagger.

normalize()[source]

Normalize the LPTN state, by dividing by \(\sqrt{Tr(rho)}\).

print_tensor_shapes(how_many=None)[source]

Prints the shape of tensors in LPTN

Parameters

how_manyint

Only the shapes of the first <how_many> tensors are printed. If how_many=None, shapes of all of the tensors are printed

Return

None

print_tensors(how_many=None)[source]

Prints the tensors in LPTN together with their shape

Parameters

how_manyint, optional

Only the first :py:name::how_many tensors are printed. If :py:name::how_many=None, all of the tensors are printed

Return

None

classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]

Construct a product (separable) state in LPTN form, given the local states of each of the sites.

Parameters

matList[np.array of rank 2]

Matrix with ii-th row being a (normalized) local state of the ii-th site. Number of rows is therefore equal to the number of sites, and number of columns corresponds to the local dimension.

paddingnp.array of length 2 or None, optional

Used to enable the growth of bond dimension in TDVP algorithms for LPTN (necessary as well for two tensor updates). If not None, all the MPS tensors are padded such that the bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. If False, the bond dimensions are equal to 1. Default to None.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new LPTN.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

LPTN

Corresponding product state LPTN.

classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]

Read an LPTN via pickle or in the old formatted way shared with the Quantum TEA fortran modules.

Parameters

filename: str

PATH to the file

tensor_backendTensorBackend

Setup which tensor class to create.

cmplx: bool, optional

If True the LPTN is complex, real otherwise. Default to True

order: str, optional

If ‘F’ the tensor is transformed from column-major to row-major, if ‘C’ it is left as read.

Returns

obj: py:class:LPTN

LPTN class read from file

Details

For the formatted format:

Read the LPTN written by FORTRAN in a formatted way on file. Reads in column-major order but the output is in row-major.

reduced_dm(sites, max_qubits=10)[source]

Get a reduced density matrix of a given LPTN. The result is in a matrix form.

Parameters

siteslist of int

Specifies the sites for the reduced density matrix. The partial trace is performed over all of the other tensors. Currently, a reduced density matrix is implemented only for single and neighbour sites. The sites are counted from zero to num_sites-1.

max_qubitsint, optional

Maximal number of qubits a reduced density matrix can have. If the number of qubits is greater, it will throw an exception. If the local Hilbert space dimension is not 2, The number of qubits is calculated as np.log2(D), where D is a total Hilbert space dimension of reduced density matrix. Default to 10.

Returns

red_dm2D np.ndarray

Reduced density matrix.

scale(factor)[source]

Multiply the tensor network state by a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network state.

scale_inverse(factor)[source]

Multiply the tensor network state by a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network state.

Update or set singvals on link via two positions.

shift_gauge_center(ind_final)[source]

Shift a gauge center of the LPTN.

ind_finallist or np.array of two ints

The new gauge center will be installed between these two sites (when considering the non-python index starting at 1).

Returns

None

site_canonize(idx, keep_singvals=False, normalize=False)[source]

Shift the isometry center to the tensor containing the corresponding site, i.e., move the isometry to a specific Hilbert space. This method can be implemented independent of the tensor network structure.

Parameters

idxint

Index of the physical site which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

normalizebool, optional

If True, normalize the state after the isometry movement. Default to False.

property tensors

List of MPS tensors

to_dense(true_copy=False)[source]

Convert into a TN with dense tensors (without symmetries).

to_mps()[source]

Converts a given LPTN into MPS if pure.

Returns

psiMPS

The wave-function as MPS if a pure density matrix.

Raises

Mixed state: if mixed-state representations are not pure, an

error will be raised.

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Decompose a given LPTN into statevector form if pure.

Parameters

qiskit_orderbool, optional

If true, the order is right-to-left. Otherwise left-to-right (which is the usual order in physics). Default to False.

max_qubit_equivalentint, optional

Maximum number of qubits for which the statevector is computed. i.e. for a maximum hilbert space of 2**max_qubit_equivalent. Default to 20.

Returns

psiinstance of _AbstractQteaTensor

The statevector of the system

Raises

Mixed state: if mixed-state representations are not pure, an

error will be raised.

to_tensor_list()[source]

Return the tensor list representation of the LPTN.

Return

list[QteaTensor]

List of tensors of the LPTN.

to_tensor_list_mps()[source]

Return the tensor list representation of the LPTN as MPS. If the upper link has dimension one, the tensors are reshaped to rank 3.

Return

list

List of tensors of the LPTN as MPS.

to_ttn()[source]

Converts LPTN to TTN

write(filename, cmplx=True)[source]

Write an LPTN in python format into a FORTRAN format, i.e. transforms row-major into column-major

Parameters

filename: str

PATH to the file

cmplx: bool, optional

If True the MPS is complex, real otherwise. Default to True

Returns

obj: py:class:LPTN

LPTN class read from file

Tree tensor operators

class qtealeaves.emulator.TTO(num_sites, convergence_parameters, local_dim=2, tensor_backend=None, initialize='ground', iso_center=None, **kwargs)[source]

TREE TENSOR OPERATOR - represents a density matrix

Parameters

num_sitesint

Number of sites

convergence_parameters:py:class::TNConvergenceParameters

Input for handling convergence parameters. In particular, in the TTO simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated

local_dimint, optional

Dimension of Hilbert space of single site (defined as the same for each site). Default is 2.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

initializestr, optional

Available are vacuum / ground, random, or empty. Options for tensor class as well allowed. Default to “ground”

iso_centerNone or np.ndarray/list of two ints, optional

Position of the gauge center. [i,j] means j-th tensor of i-th layer, i=0 is uppermost, j=0 is the leftmost tensor. If TTO has no gauge center, iso_center = None. Default is None.

Initialization

|000...000><000---000| , where Z|0>=|0>

Tensor representation


/ /
O O
/ } –> complex conjugates of tensors below,

O access with TTO.cc_layers.tensors | O

/ } –> these are contained in TTO.layers

O O

/ /

Attributes

TTO.num_sitesint

Number of sites in TTO

TTO.local_dimnp.ndarray of ints

Local Hilbert space dimension

TTO.num_layersint

Number of layers in TTO

TTO.layerslist of :py:class::TTOLayer-s

Layers of the TTO, list of ‘TTOLayer’ objects

TTO.cc_layerslist of :py:class::TTOLayer-s

Complex conjugate part of the TTO, list of ‘TTOLayer’ objects

TTO.probabilitiesnp.ndarray of float

Mixed state probabilities for the case when TTO is a density matrix.

TTO.iso_centerNone or np.ndarray/list of two ints

Position of the gauge center. [i,j] means j-th tensor of i-th layer, i=0 is uppermost, j=0 is the leftmost tensor. If the TTO has no gauge center, TTO.iso_center = None.

TTO._max_bond_dimint

Maximal bond dimension

TTO._cut_ratiofloat

Cut ratio

Access to tensors

  • access to i-th layer with TTO[i]

    [ uppermost layer is indexed with i = 0 ]

  • access to [i,j]-th tensor with TTO[i][j]

    [ leftmost tensor is indexed with j = 0 ]

  • order of legs in tensor

    [ left leg - right leg - upper leg]

apply_local_kraus_channel(kraus_ops)[source]

Apply local Kraus channels to tensor network

Parameters

kraus_opsdict of QTeaTensor

Dictionary, keys are site indices and elements the corresponding 3-leg kraus tensors

Returns

singvals_cut: float

Sum of singular values discarded due to truncation.

property cc_layers

complex conjugate part of TTO, returns complex conjugate tensors stored in TTOLayers

concurrence()[source]

This function calculates the concurrence entanglement monotone for two qubits:

C(rho) = sqrt(sqrt(rho)*rho_tilde*sqrt(rho)),

where rho is a density matrix and rho_tilde is (sigma_y sigma_y) rho* (sigma_y sigma_y).

Parameters

self:pyclass:`TTO`

Two-qubit density matrix TTO.

Returns

concfloat

The concurrence entanglement monotone of a given TTO.

contract(other, boundaries=None)[source]

Contract the TTO self with another TN other <other|self>. By default it is a full contraction, but also a partial contraction is possible. If TTO is not pure, tensor will be returned even if boundaries is None.

Parameters

other_AbstractTN (currently only MPS enabled)

other ansatz to contract with

boundariestuple of ints, optional (currently only None enabled)

Contract to MPSs from boundaries[0] to boundaries[1]. In this case the output will be a tensor. Default to None, which is full contraction

Returns

contractioncomplex | AbstractQteaTensor

Result of the contraction

classmethod dm_to_tto(num_sites, dim, psi, prob, conv_params=None, padding=None, tensor_backend=None)[source]

Computes the TTO form of a given density matrix

Parameters

num_sitesint

Number of sites

dimint

Local Hilbert space dimension

psi,probmatrix or vector, matrix or int
  • Mixed states :

    psi is a matrix with eigenstates as columns, prob is 1D array containing (possibly truncated) probabilities for each state

  • Pure states : psi is a state, prob = 1

conv_params:py:class::TNConvergenceParameters

Input for handling convergence parameters. in particular, we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated

paddingnp.array of length 2 or None, optional

Used to increase the bond dimension of the TTO. Also necessary to allow the growth of bond dimension in TDVP algorithms (two tensor updates). If not None, all the TTO tensors are padded such that the maximal bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

rho_ttTTO

TTO form of the density matrix

dot(other)[source]

Not implemented

entropy(prob=None, local_dim=2, eps=1e-10)[source]

This function calculates Von Neumann entropy of a TTO mixed state density matrix. entropy = -sum(prob log(prob)), where prob are the mixed state probabilities and logarithm base is local_dim.

Parameters

probnp.ndarray, optional

Mixed state probabilities. If given, the entropy is calculated faster. Default is None.

local_dimint, optional

Dimension of local Hilbert space. Default is 2.

epsfloat, optional

To make calculation faster and avoid division by zero, all the probabilities smaller than <eps> are cut off. Default is 1e-10.

Return

entropyfloat

Von Neumann entropy of a TTO density matrix.

eof(init_guess=None, unitary=None, extra=0, maxiter=300)[source]

This function estimates entanglement of formation (EoF) of a TTO mixed state density matrix.

Definition: EoF = min( sum( p_j * E( psi_j ) ) ), where the minimum is found over all the possible decompositions of density matrix to states psi_j and corresponding probabilities p_j. E() is the entropy of entanglement with respect to two halves of the system.

Parameters

extraint, optional

The minimization for computing EoF is run over unitary matrices of dimension K0 x k_dim, where k_dim = K0 + <extra>, K0 is the number of probabilities kept in a mixed state density matrix. Default is 0.

init_guessnp.ndarray or list of real numbers, optional

Initial entries for elements of Hermitian matrix needed for constructing the unitary matrix. First k_dim entries are the values on the diagonal. Next (k_dim^2-k_dim)/2 entries are the values for real part of matrix elements above the diagonal. Next (k_dim^2-k_dim)/2 entries are the values for imaginary part of matrix elements above the diagonal. When initializing the Hermitian matrix, the elements above the diagonal will be filled with the values from <init_guess> list row by row. Default is None.

unitary2D np.ndarray, 1st axis dimension must be equal to the

number of probabilities kept in a density matrix, optional

The EoF is computed only for the density matrix decomposition defined with this unitary matrix and no optimization is done. Either init_guess or unitary must be specified. Default is None.

maxiterint, optional

Maximal number of iterations for minimization. Default is 300.

Return

eoffloat

An estimate of the EoF of a given mixed state density matrix.

Only if init_params is not None: params.x : np.ndarray

Optimal solution for entries for Hermitian matrix defining the decomposition of density matrix.

classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

Computes the TTO form of a given density matrix

Parameters

num_sitesint

Number of sites

dimint

Local Hilbert space dimension

psi,probmatrix or vector, matrix or int
  • Mixed states :

    psi is a matrix with eigenstates as columns, prob is 1D array containing (possibly truncated) probabilities for each state

  • Pure states : psi is a state, prob = 1

conv_params:py:class::TNConvergenceParameters

Input for handling convergence parameters. in particular, we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated

paddingnp.array of length 2 or None, optional

Used to increase the bond dimension of the TTO. Also necessary to allow the growth of bond dimension in TDVP algorithms (two tensor updates). If not None, all the TTO tensors are padded such that the maximal bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

rho_ttTTO

TTO form of the density matrix

classmethod from_lptn(lptn, conv_params=None, tensor_backend=None, method='moving', **kwargs)[source]

Converts LPTN to TTO.

Parameters

lptn: LPTN

Object to convert to TTO.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters If None, the algorithm will try to extract conv_params from lptn.convergence_parameters. Default is None.

kwargsadditional keyword arguments

They are accepted and passed to the conversion method for LPTN to TTO.

Return

tto: TTO

Decomposition of lptn.

classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Converts MPS to TTO.

Parameters

mps: MPS

object to convert to TTO.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

Return

tto: TTO

Decomposition of mps.

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Initialize the TTO by decomposing a statevector into TTO form.

We use the dm_to_tto function instead of mapping the statevector to TTN and the TTN to TTO since in this way we avoid the problems arising from the different structures of the top layer.

Parameters

statevectorndarray of shape( [local_dim]*num_sites, )

Statevector describing the interested state for initializing the TTN

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]

Converts TTN to TTO.

Parameters

ttn: TTN

object to convert to TTO.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

tto: TTO

Decomposition of ttn.

classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Converts TTO to TTO.

Parameters

tto: TTO

Object to convert to TTO.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters. Default is None.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

Return

new_tto: TTO

Decomposition of tto, here just a copy.

get_eigenstates(eigen_num_ll)[source]

Extracts the eigenstates from the input TTO.

Parameters

ttoTTO

The input TTO from which the eigenvector is extracted.

eigen_num_lllist of int

The list of indices corresponding to the eigenstates to be extracted from the TTO.

Returns

ttn_listlist of TTN

The extracted eigenstates in TTN format.

prob_list: list of float

The corresponding probabilites.

install_gauge_center()[source]

Install a gauge center to the position [0,0] (uppermost tensor) of the TTO.

Return

None

kron(other, inplace=False, fill_identity=True)[source]

Concatenate two TTO, taking the kronecker/outer product of the two states.

Parameters

otherTTO

TTO to concatenate

inplacebool, optional

If True apply the kronecker product in place. Instead, if inplace=False give as output the product. Default to False.

fill_identityBool

If True, uppermost layer tensors are simply set to identity tensors. Otherwise, constructs last layer by QR-ing the top tensors of self and other. Defatult to True

Returns

TTO

Concatenation of the first TTO with the second.

property local_dim

The local dimension is constrained to be always the same on the TTO

log_negativity(sqrt=False, local_dim=2)[source]

Logarithmic negativity

classmethod lptn_to_tto(tensor_list, conv_params, tensor_backend)[source]

Transforms the density matrix from LPTN to TTO form

Parameters

tensor_listlist

Tensors in LPTN, LPTN.tensors

conv_paramsTNConvergenceParameters

Input for handling convergence parameters in particular, we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

ttoTTO

TTO form of the input LPTN

classmethod lptn_to_tto_iso(tensor_list, conv_params, tensor_backend)[source]

Transforms the density matrix from LPTN to TTO form, keeping the TN isometrized throughout the procedure.

Parameters

tensor_listlist

List of tensors in LPTN, LPTN.tensors.

conv_paramsTNConvergenceParameters

Input for handling convergence parameters in particular, we are interested in: - the maximum bond dimension (max_bond_dimension) - the maximum Kraus dimension (max_kraus_dimension), i.e., Dimension of link connecting two sides of TTO (upper link of the root tensor). - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated.

Return

ttoTTO

TTO form of the input LPTN

norm_trackfloat

Norm of the TTO obtained by keeping the track of singular value truncations. Note that this is not the actual norm of the TTO, as the singular values are renormalized after each truncation and therefore actual norm is kept to 1. Higher values are better, norm_track of 1 means no truncations.

classmethod lptn_to_tto_move_tensors(tensor_list, conv_params, tensor_backend)[source]

Transforms the density matrix from LPTN to TTO form.

Parameters

tensor_listlist

Tensors in LPTN, LPTN.tensors

conv_paramsTNConvergenceParameters

Input for handling convergence parameters in particular, we are interested in: - the maximum bond dimension (max_bond_dimension) - the maximum Kraus dimension (max_kraus_dimension), i.e., Dimension of link connecting two sides of TTO (upper link of the root tensor). - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that lambda/lambda_max <= eps are truncated

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

ttoTTO

TTO form of the input LPTN

norm_trackfloat

Norm of the TTO obtained by keeping the track of singular value truncations. Note that this is not the actual norm of the TTO, as the singular values are renormalized after each truncation and therefore actual norm is kept to 1. Higher values are better, norm_track of 1 means no truncations.

Details

LPTN + TTO
                     |
                     1
                    /                                /                                 1     1
                 / \   /                             /  |   |                             1   1   1   1
  |  |  |  |  /\  / \ / \ / \  |  |  |  |
--L--L--L--L--               --L--L--L--L--
  |  |  |  |                   |  |  |  |
LPTN after QR + TTO
                     |
                     1
                    /                                /                                 1     1
                 / \   /                             /  |   |                             1   T   T   1
              /\  / \ / \ / \           |
--R--R--R--R--               --R--R--R--L--
  |  |  |  |                   |  |  |  |
  Q  Q  Q  Q                   Q  Q  Q
 /| /| /| /|                  /| /| /|

with

  • L: being an original LPTN site

  • 1: being identities with two links at chi and one trivial

    link. chi is the bond dimension at the center of the LPTN. The links with chi point to the LPTN halves.

  • T : trivial tensor with all link identical irreps.

  • R, Q: separating the horizontal links in the LPTN.

The algorithm now:

  1. Move tensor R to the top (we can move an additional leg easily)

  2. Contract Q and merge the Kraus link of the top tensor with the Kraus link inside Q.

  3. New top tensor has four links, move Hilbert-space link down to its position in the TTO.

  4. Remove dummy link and keep local link just moved down.

  5. Re-iterate.

Procedure for last tensor is sligthly modified.

meas_bond_entropy()[source]

Measure the entropy(!) along all possible connected partitions of the TTO using the Von Neumann entropy, which is not an entanglement measure if the state is mixed. Von Neumann entropy \(S_V\) is defined as:

\[S_V = - \sum_i^{\chi} s^2 \log2( s^2)\]

with \(s\) the singular values

Return

measuresdict

Keys are the range of sites to which the entropy corresponds

ml_default_sweep_order(num_tensor_rule)[source]

Default sweep order for a machine learning optimization, where we replace the ground state sweep order.

Arguments

num_tensor_rule: int

Specify if it is a one-tensor or two-tensor update.

Returns

sweep_orderList

List of tensor positions compatible with the corresponding ansatz. For two-site rules, each pair is optimized once which skips the last position in respect to the ground state search for the two-tensor update.

ml_get_gradient_single_tensor(pos)[source]

Get the gradient w.r.t. to the tensor at pos similar to the two-tensor version.

Parameters

postuple of two ints

Layer index and tensor index withn layer of the tensor to work with.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

ml_get_gradient_two_tensors(pos, pos_p=None)[source]

Get the gradient w.r.t. the tensors at position idx, idx+1 of the MPS following the procedure explained in https://arxiv.org/pdf/1605.05775.pdf for the data_sample given

Parameters

idxint

Index of the tensor to optimize

pos_pint | None

Index of partner tensor. If None, error will be raised as we prefer the good ordering.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset, has_trivial_label_link=True, has_env_label_link=False)[source]

Generate an initial guess for a tensor network machine learning approach.

Arguments

convergence_parametersTNConvergenceParameters

Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.

tensor_backendTensorBackend

Selecting the tensor backend to run the simulations with.

initializestr

The string superposition-data will trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.

ml_data_mpoMLDataMPO

MPO of the labeled data set to be learned including the labels.

datasetList[MPS]

Data set represented as list of MPS states. Same order as in ml_data_mpo.

has_trivial_linkbool

With a trivial link (True), the ML-MPS learns solely based on the overlap of the sample with the ansatz rounded to the closest integer. Instead, the typical ML approach with argmax over a vector is used with has_trivial_link=False.

has_env_label_linkbool, optional

Move label link into the environment, which means here having a non-trivial link towards the environment in the ansatz. Default to False.

Returns

ansatz_AbstractTN

Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.

ml_reorder_pos_pair(pos, pos_partner, link_pos, link_partner)[source]

TTO order is with lower-layer tensor first (but higher layer-index).

Arguments

posint | tuple[int]

Position of the first tensor in the network.

pos_partnerint | tuple[int]

Position of the partner tensor in the network.

link_posint

Link in tensor connecting to partner tensor.

link_partnerint

Link in partner tensor connecting to tensor.

Returns

pos, pos_partner, link_pos, link_partner

Re-ordering of tensor and partner tensor if beneficial.

ml_to_id_step(pos, pos_p)[source]

Construct the id_step variables to shift effective operators given two positions in the tensor network.

Arguments

postuple[int]

First position in the TTO.

pos_ptuple[int]

Second position in the TTO.

Returns

id_steplist[int]

Compatible step with TTO, i.e., list of [src_layer, src_tensor, src_link, dst_layer, dst_tensor, dst_link].

ml_two_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with two tensors and the label link in the environment.

Parameters

postuple(int)

Position of the tensor to be optimized in the network.

num_grad_stepsint

Number of steps as loop in the gradient descent.

Returns

lossfloat (as native data type of the backend on the CPU)

Value of the loss function.

classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]

Broadcast a whole tensor network.

Arguments

stateTTO (for MPI-rank root, otherwise None is acceptable)

State to be broadcasted via MPI.

commMPI communicator

Send state to this group of MPI processes.

tensor_backendTensorBackend

Needed to identity data types and tensor classes on receiving MPI threads (plus checks on sending MPI thread).

rootint, optional

MPI-rank of sending thread with the state. Default to 0.

static mpi_sample_n_unique_states(state, num_unique, comm, tensor_backend, cache_size=None, cache_clearing_strategy=None, filter_func=None, mpi_final_op=None, root=0, **kwargs)[source]

Try sampling a target number of unique states from TN ansatz.

negativity(sqrt=False)[source]

Computes the negativity entanglement monotone for a mixed state density matrix in the TTO form.

  • Measures the entanglement between the left and right half of

the 1D system.

Parameters

sqrtBoolean

Mathematically, negativity can be computed in two different ways. If True, it is computed via the square of partially transposed density matrix, and if False, it is computed via the eigenvalues of partially transposed density matrix.

Return

negfloat

Negativity of the TTO.

property probabilities

Extracts the mixed, e.g. finite temperature, state probabilities from a TTO density matrix.

Return

probnp.ndarray

Mixed state probabilities in descending order.

classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]

Construct a pure product state in TTO form, given the local states of each of the sites.

Parameters

mat2D np.array

Matrix with ii-th row being a (normalized) local state of the ii-th site. Number of rows is therefore equal to the number of sites, and number of columns corresponds to the local dimension.

paddingnp.array of length 2 or None, optional

Used to increase the bond dimension of the TTO. Also necessary to allow the growth of bond dimension in TDVP algorithms (two tensor updates). If not None, all the TTO tensors are padded such that the maximal bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. Default to None.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new TT0.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

prod_ttoTTO

Corresponding product state TTO.

classmethod product_state_from_local_states_2d(mat_2d, padding=None, mapping='HilbertCurveMap', return_map=False, convergence_parameters=None, tensor_backend=None)[source]

Construct a pure product state in TTO form, given the local states of each of the sites.

Parameters

mat_2dnp.array of rank 2

Array with third axis being a (normalized) local state of the (ii,jj)-th site (where ii and jj are indices of the first and second axes). Product of first two axes’ dimensions is therefore equal to the total number of sites, and third axis dimension corresponds to the local dimension.

paddingnp.array of length 2 or None, optional

Used to increase the bond dimension of the TTO. Also necessary to allow the growth of bond dimension in TDVP algorithms (two tensor updates). If not None, all the TTO tensors are padded such that the maximal bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. Default to None.

mappingstring or instance of HilbertCurveMap,

optional

Which 2d to 1d mapping to use. Possible inputs are: ‘HilbertCurveMap’, ‘SnakeMap’, and ‘ZigZagMap’. Default is ‘HilbertCurveMap’.

return_mapboolean, optional

If True, the function returns array map with indices of 2d to 1d mapping. Default to False.

convergence_parametersTNConvergenceParameters, optional

Convergence parameters for the new TTO.

Return

prod_ttoTTO

Corresponding product state TTO.

mapnp.array, returned only if return_map==True

Nx2 Matrix, where N is a total number of particles. The values in the ii-th row of the matrix denote particle’s position in a corresponding 2d grid.

purity(prob=None)[source]

Computes the purity entanglement monotone for a density matrix in the TTO form.

purity = Tr(rho^2), where rho is a density matrix. The above relation is equivalent to: purity = sum(prob^2), where prob are mixed state probabilities.

Parameters

probnp.ndarray, optional

Mixed state probabilities. If given, purity is calculated with them. If None, the probabilities are calculated from the TTO. Default is None.

Return

float :

Purity of the TTO density matrix.

classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]

Read a TTO in a unformatted way via pkl (formatted files are not supported by TTOs).

Parameters

filename: str

PATH to the file

tensor_backendTensorBackend

Setup which tensor class to create.

cmplx: bool, optional

If True the TTO is complex, real otherwise. Default to True

order: str, optional

If ‘F’ the tensor is transformed from column-major to row-major, if ‘C’ it is left as read.

Returns

obj: py:class:TTO

TTO class read from file

classmethod read_v0_2_29(filename, tensor_backend, cmplx=True, order='F')[source]

Not implemented

renyi_entropy(alpha, prob=None, local_dim=2, eps=1e-10)[source]

This function calculates Renyi entropy of order alpha for a TTO mixed state density matrix. Renyi entropy = 1/(1-alpha)*sum(log(prob**alpha)), where prob are the mixed state probabilities and logarithm base is local_dim

Parameters

alphafloat

order of Renyi entropy.

probnp.ndarray, optional

Mixed state probabilities. If given, the entropy is calculated faster. Default is None.

local_dimint, optional

Dimension of local Hilbert space. Default is 2.

epsfloat, optional

To make calculation faster and avoid division by zero, all the probabilities smaller than <eps> are cut off. Default is 1e-10.

Return

entropyfloat

Alpha-order Rényi entropy of the given TTO density matrix.

shift_gauge_center(ind_final, keep_singvals=False)[source]

Shift a gauge center of the TTO to a given position.

Parameters

ind_finallist or np.array of lenght 2

Index where we want the new gauge center to be.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

Returns

None

**Remark[i,j] means j-th tensor of i-th layer, i=0 is uppermost, j=0 is

the most left tensor

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Decompose a given pure state TTO (projector) into statevector form.

Parameters

qiskit_orderbool, optional

If true, the order is right-to-left. Otherwise left-to-right (which is the usual order in physics). Default to False.

max_qubit_equivalentint, optional

Maximum number of qubits for which the statevector is computed. i.e. for a maximum hilbert space of 2**max_qubit_equivalent. Default to 20.

Returns

psiinstance of _AbstractQteaTensor

The statevector of the system

to_tensor_list()[source]

Not implemented

to_ttn()[source]

Converts a pure state TTO (projector) into a TTN.

tree(matrix_in, conv_params)[source]

Transforms a given matrix into a tensor network as below:

        |
|       O
O ---> /             |     O   O
      |   |

the first index of a matrix corresponds to the lower leg of the input tensor

Parameters

selfTTO

Initialized TTO for which the tree method is used. From it, the local dimension and convergence parameters for SVD are extracted.

matrix_inndarray

Matrix to be transformed.

conv_params[TNConvergenceParameters]

Input for handling convergence parameters.

Returns

tens_left, tens_mid, tens_rightndarray

Tensors of the second TN on the picture above, read from left to right. –> order of indices:

tens_left, tens_right - [lower, upper] tens_mid - [lower left, upper, lower right]

trunc_probabilities(return_singvals=False)[source]

Truncates the mixed state probabilities of a TTO.

Parameters

return_singvalsBoolean, optional

If True, the truncated singualr values are returned.

Return

singvals_cutfloat, returned if `return_singvals`==True

Discarded singular values due to the truncation.

classmethod ttn_to_tto(ttn, conv_params=None, no_truncation=True, padding=None, tensor_backend=None)[source]

Converts a state (TTN) to the respective projector (TTO).

Parameters

ttnTTN

The TTN to be converted.

conv_paramsTNConvergenceParameters, optional

Convergence parameters for the resulting TTO. If None is given, then use the convergence parameters of the input TTN. Default to None.

no_truncationboolean, optional

Allows to run SVD without truncation. Default to True.

paddingnp.array of length 2 or None, optional

Used to increase the bond dimension of the TTO. Also necessary to allow the growth of bond dimension in TDVP algorithms (two tensor updates). If not None, all the TTO tensors are padded such that the maximal bond dimension is equal to padding[0]. The value padding[1] tells with which value are we padding the tensors. Note that padding[1] should be very small, as it plays the role of numerical noise. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Returns

ttoTTO

TTO form of the input TTN

unset_all_singvals()[source]

Unset all the singvals in the TTO due to a local operation that is modifying the global state and the entanglement structure, such as a projective measurement.

Returns

None

write(filename, cmplx=True)[source]

Not implemented

Augmented tree tensor networks

class qtealeaves.emulator.ATTN(num_sites, convergence_parameters, local_dim=2, requires_singvals=False, tensor_backend=None, initialize='random', sectors=None, de_sites=None, de_initialize='identity', check_unitarity=True)[source]

Augmented tree tensor network class = TTN + disentangler gates.

Parameters

num_sitesint

Number of sites

convergence_parameters: TNConvergenceParameters

Class for handling convergence parameters. In particular, in the aTTN simulator we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular

values are neglected, i.e. if \(\lamda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)

local_dim: int, optional

Local Hilbert space dimension. Default to 2.

requires_singvalsboolean, optional

Allows to enforce SVD to have singular values on each link available which might be useful for measurements, e.g., bond entropy (the alternative is traversing the whole TN again to get the bond entropy on each link with an SVD).

tensor_backendNone or instance of TensorBackend, optional

Default for None is QteaTensor with np.complex128 on CPU.

initializestring, optional

Define the initialization method. For random entries use ‘random’, for empty aTTN use ‘empty’. Default to ‘random’.

sectorsdict, optional

[Not Implemented for aTTN] For restricting symmetry sector and/or bond dimension in initialization. If empty, no restriction. Default to empty dictionary.

de_sites2d np.array, optional

Array with disentangler positions with n rows and 2 columns, where n is the number of disentanglers. Counting starts from 0 and indices are passed as in the mapped 1d system. If set to ‘auto’, the disentangler positions are automatically selected to fit as much disentanglers as possible. Default to ‘random’.

de_initializestring, optional

Define the initialization method. For identities use ‘identity’, for random entries use ‘random’. Default to ‘identity’.

check_unitarityBoolean, optional

If True, all the disentangler tensors are checked for unitarity and an error is raised if the check fails. Default to True.

Details

Notation: the last layer in TTN contains the local Hilbert spaces and the most tensors. The order of legs in TTN is:

|2

0| |1

The order of legs in disentanglers is: 0,1 are attached to <psi|, and 2,3 are attached to |psi>, so that it matches the notation DE|psi>.

apply_des_to_hamiltonian(params)[source]

Contracts the disentanglers to the hamiltonian. Params needed for the creation of the DenseMpo representation of the disentangler in contract_de_layer(). Updates the eff_op of self in place.

convert(dtype, device)[source]

Convert data type and device inplace.

from_attn(include_disentanglers=True)[source]

NOTE: For now works only for include_disentanglers = False.

Create TTN from aTTN.

Parameters

include_disentanglersBoolean, optional

If True, TTN will be constructed by contracting the disentanglers to the TTN part of aTTN. If False, only the TTN part of the aTTN is returned, regardless of the disentanglers. Default to True.

truncationBoolean

Whether to truncate throughout the process of applying the disentangler.

Return

new_ttnTTN

Resulting TTN.

classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

Create an aTTN from a density matrix, which is not implemented yet.

classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]

Create an aTTN from LPTN, which is not implemented yet.

classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Create an aTTN from MPS, which is not implemented yet.

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None, check_unitarity=True)[source]

Initialize an aTTN by decomposing a statevector into TTN form with 0 disentanglers.

Parameters

statevectorndarray of shape( [local_dim]*num_sites, )

Statevector describing the interested state for initializing the TTN

devicestr, optional

Device where the computation is done. Either “cpu” or “gpu”.

tensor_clstype for representing tensors.

Default to QteaTensor

classmethod from_ttn(ttn, conv_params=None, de_sites=None, de_initialize='identity', check_unitarity=True, **kwargs)[source]

Create aTTN from an existing TTN.

Parameters

ttnTTN

TTN part of the new aTTN

de_siteslist or np.array

Positions of disentanglers.

de_initializestr

Method of disentangler initialization.

kwargsadditional keyword arguments

They are accepted, but not passed to calls in this function.

classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Create an aTTN from , which is not implemented yet.

get_environment(de_site, relevant_tpo_ids)[source]

Gets the left and right environment for the DE optimization by partially contracting the network of <psi|H|psi>.

First, we pick an ‘anchor’, the tensor which separates the left and right environment. Then, we iteratively contract into env_left everything between the tensor attached to the first de_site and the anchor, and similarly into the right.

Parameters

de_site2d np.array

Position of the disentangler which is to be optimized. A list of two ints, corresponding to the position of the two tensors in the lowest layer of the ttn that are attached to it.

relevant_tpo_idslist[ int ]

List of TPO-IDs we care about, because they are present at the disentangler sites. All contraction are filtered to only include these IDs.

Return

env_l, env_riTPO

Left and right environment

get_indices_from_de_position(de_position)[source]

Given the position of a disentangler, returns the indices and links of the two tensors that couple to it.

Parameters

de_positionlist[int]

position of the disentangler

Returns

ndx1, ndx2int

indices of the two tensors that couple to the DE

link1, link2int

links at which the DE is attached

get_iterative_contraction_path(path, anchor, include_anchor)[source]

Collects the information required for an iterative contraction along a path, which is slightly different than what get_path() provides. At each step of the contraction, you need:

  • this_position : the position of the tree tensor

  • incoming_linkthe link where the path comes into the tree

    This is the link along which the tensor is contracted into env.

  • outgoing_linkthe link where the path continues

    This link becomes the outgoing link of the new env.

  • offpath_linkthe link pointing away from the path

    This is where the eff_op of the rest of the network is contracted.

  • offpath_positionthe position of the tree tensor away from the path

    This is required for the identification of the effective operator.

The path for contraction ends at the anchor (including it or not), which is set by the anchor and include_anchor arguments.

pathlist[ list[] ]

The path as it comes from the get_path() method.

anchortuple[ int ]

Position of the anchor as (layer, index).

include_anchorbool

Whether to include the anchor as the last element or not.

Returns

result : list[ tuple[ int | tuple[int] ] ] The list of tuples of integers. this_position and offpath_position are tuples of (layer, index), the rest are integers.

get_rho_i(idx)[source]

Get the reduced density matrix of the site at index idx.

Parameters

idxint

Index of the site

iteratively_contract_along_path(env, path, relevant_tpo_ids)[source]

Given the initial object env, iteratively contracts the tree network along the specified path. In each step takes contracts a tree tensor on the path with its effective operator on the link not on the path, and contracts this object into env. Then contracts the conjugate of the tree tensor into env. The resulting object has the same leg ordering as the input env.

envITPO

The initial point of the iteration. Contracted first TTN tensor, MPO, and conj(tensor).

pathlist[ list[] ]

Path along which to perform the iterative contraction.

relevant_tpo_idslist[ int ]

List of TPO-IDs we care about, because they are present at the disentangler sites. All contraction are filtered to only include these IDs.

Returns

env : ITPO The full object representing the environment of a disentangler contracted along the given path.

kron(other, inplace=False, fill_identity=True)[source]

Concatenate two aTTN, taking the kronecker/outer product of the two states. The bond dimension assumed is the maximum between the two bond dimensions. For now, the restriction is that self and other must have the same number of layers. Idea for future implementation : allow other to be a TTN.

Parameters

otheraTTN

aTTN to concatenate

inplacebool, optional

If True apply the kronecker product in place. Instead, if inplace=False give as output the product. Default to False.

fill_identityBool

If True, uppermost layer tensors are simply set to identity tensors. Otherwise, constructs last layer by QR-ing the top tensors of self and other. Defatult to True

Returns

aTTN

Concatenation of the first aTTN with the second.

meas_local(op_list)[source]

Measure a local observable along sites of the aTTN, excluding the sites with the disentangler (because there the measurement is not local anymore)

Parameters

op_listlist of _AbstractQteaTensor

local operator to measure on each site

Return

measuresndarray, shape (num_sites)

Measures of the local operator along each site except sites with the disentanglers. At the disentangler sites measures is set to zero.

optimize_de_site(de_site, de_index)[source]

Optimize the disentangler on a given site. See the aTTN cookbook for details. For optimizing a given disentangler, we contract its environment (the full <psi|H|psi> network excluding the disentangler), and then set the disentagler to one which minimizes the energy.

Parameters

de_site2d np.array

Position of the disentangler to be optimized.

de_indexint

The index of the disentangler in the list of disentanglers. Its tensor is then as self.de_layer[de_index].

Return

None (the aTTN disentangler is updated in-place)

optimize_disentanglers()[source]

Finds the optimal set of disentanglers for a given aTTN and Hamiltonian model. Used in the aTTN groundstate search.

Return

None (the aTTN is updated in-place)

set_cache_rho()[source]

Cache the reduced density matrices for faster access.

start_environment_contraction_for_de_optimization(index, de_link, relevant_tpo_ids)[source]

Implementation of the pre_contr_dopt_binary_tree() fortran routine. Does the first step of contracting the environment for the disentangler optimization: contracts the tensor where the disentangler is attached to the MPO operator on the OTHER leg, and then with the complex conjugate of the same tensor. An iterative contraction of the tree along the path can then be performed on this object.

Order of legs documented at the end of the function.

See the aTTN cookbook. Assumes a binary tree.

Parameters

indexint

Index of the tensor coupled to the disentangler in the lowest layer. It will be contracted with the mpo on the leg without the disentangler.

de_link : int The link of the tensor at index that attaches to the disentangler.

relevant_tpo_idslist[ int ]

List of TPO-IDs we care about, because they are present at the disentangler sites. All contraction are filtered to only include these IDs.

Returns

resultiTPO

The result of the contraction. With this object you can start the iterative contraction of the tree, which leads to obtaining the left/right_environment.

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Decompose a given aTTN into statevector form.

Parameters

qiskit_orderbool, optional

If true, the order is right-to-left. Otherwise left-to-right (which is the usual order in physics). Default to False.

max_qubit_equivalentint, optional

Maximum number of qubits for which the statevector is computed. i.e. for a maximum hilbert space of 2**max_qubit_equivalent. Default to 20.

Returns

psiinstance of _AbstractQteaTensor

The statevector of the system

MPI version of matrix product states

class qtealeaves.emulator.MPIMPS(num_sites, convergence_parameters, local_dim=2, initialize='vacuum', tensor_backend=None)[source]

MPI version of the MPS emulator that divides the MPS between the different nodes

Parameters

num_sites: int

Number of sites

convergence_parameters: TNConvergenceParameters

Class for handling convergence parameters. In particular, in the MPS simulator we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular

values are neglected, i.e. if \(\lamda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)

local_dim: int or list of ints, optional

Local dimension of the degrees of freedom. Default to 2. If a list is given, then it must have length num_sites.

initialize: str, optional

The method for the initialization. Default to “vacuum” Available: - “vacuum”, for the |000…0> state - “random”, for a random state at given bond dimension

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

apply_one_site_operator(op, pos)[source]

Applies a one operator op to the site pos of the MPIMPS. Instead of communicating the changes on the boundaries we perform an additional contraction.

Parameters

op: numpy array shape (local_dim, local_dim)

Matrix representation of the quantum gate

pos: int

Position of the qubit where to apply op.

apply_projective_operator(site, selected_output=None, remove=False)[source]

Apply a projective operator to the site site, and give the measurement as output. You can also decide to select a given output for the measurement, if the probability is non-zero. Finally, you have the possibility of removing the site after the measurement.

Parameters

site: int

Index of the site you want to measure

selected_output: int, optional

If provided, the selected state is measured. Throw an error if the probability of the state is 0

remove: bool, optional

If True, the measured index is traced away after the measurement. Default to False.

Returns

meas_state: int | None

Measured state or None if site not in this part of the MPI-MPS.

state_probfloat | None

Probability of measuring the output state or None if site not in this part of the MPI-MPS.

apply_two_site_operator(op, pos, swap=False, svd=None, parallel=None)[source]

Applies a two-site operator op to the site pos, pos+1 of the MPS. Then, perform the necessary communications between the interested process and the process

Parameters

op: numpy array shape (local_dim, local_dim, local_dim, local_dim)

Matrix representation of the quantum gate

pos: int or list of ints

Position of the qubit where to apply op. If a list is passed, the two sites should be adjacent. The first index is assumed to be the control, and the second the target. The swap argument is overwritten if a list is passed.

swap: bool

If True swaps the operator. This means that instead of the first contraction in the following we get the second. It is written is a list of pos is passed.

svdNone

Required for compatibility. Can be only True.

parallel: None

Required for compatibility. Can be only True

Returns

singular_values_cutted: ndarray

Array of singular values cutted, normalized to the biggest singular value

classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Serially decompose the statevector and then initialize the MPS

classmethod from_tensor_list(tensor_list, conv_params=None, tensor_backend=None)[source]

Initialize the MPS tensors using a list of correctly shaped tensors

Parameters

tensor_listlist of ndarrays or cupy arrays

List of tensor for initializing the MPS

conv_paramsTNConvergenceParameters, optional

Convergence parameters for the new MPS. If None, the maximum bond bond dimension possible is assumed, and a cut_ratio=1e-9. Default to None.

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Returns

objMPIMPS

The MPIMPS class

get_tensor_of_site(idx)[source]

Retrieve tensor of specifc site.

meas_local(op_list)[source]

Measure a local observable along all sites of the MPS

Parameters

op_listlist of _AbstractQteaTensor

local operator to measure on each site

Return

measuresndarray, shape (num_sites)

Measures of the local operator along each site on rank-0

property mpi_dtype

Return the MPI version of the MPS dtype (going via first tensor)

mpi_gather_tn()[source]

Gather the tensors on process 0. We do not use MPI.comm.Gather because we would gather lists of np.arrays without using the np.array advantages, making it slower than the single communications.

Returns

list on np.ndarray or None

List of tensors on the rank 0 process, None on the others

mpi_scatter_tn(tensor_list)[source]

Scatter the tensors on process 0. We do not use MPI.comm.Scatter because we would gather lists of np.arrays without using the np.array advantages, making it slower than the single communications.

Parameters

tensor_listlist of lists of np.ndarrays

The index i of the list is sent to the rank i

Returns

list on np.ndarray or None

List of tensors on the rank 0 process, None on the others

reinstall_isometry_parallel(num_cycles)[source]

Reinstall the isometry by applying identities to all even sites and to all odd sites, and repeating for num_cycles cycles. The reinstallation is exact for num_cycles=num_sites/2. Method from https://arxiv.org/abs/2312.02667

This step is serial because we have to serially pass the information along the MPS. It cannot be parallelized.

Parameters

num_cycles: int

Number of cycles for reinstalling the isometry

Returns

None

reinstall_isometry_serial(left=False, from_site=None)[source]

Reinstall the isometry center on position 0 of the full MPS.

This step is serial because we have to serially pass the information along the MPS. It cannot be parallelized.

Parameters

left: bool, optional

If True, reinstall the isometry to the left. If False, to the right. Defaulto to False

from_site: int, optional

The site from which the isometrization should start. By default None, i.e. the other end of the MPS chain.

Returns

None

to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Serially compute the statevector

Parameters

qiskit_order: bool, optional

weather to use qiskit ordering or the theoretical one. For example the state |011> has 0 in the first position for the theoretical ordering, while for qiskit ordering it is on the last position.

max_qubit_equivalent: int, optional

Maximum number of qubit sites the MPS can have and still be transformed into a statevector. If the number of sites is greater, it will throw an exception. Default to 20.

Returns

np.ndarray or None

Statevector on process 0, None on the others

to_tensor_list()[source]

Return the tensor list of the full MPS. Thus, here there are communications between the different processes and all the tensorlist is returned on process 0

Returns

list of np.ndarray or None

List of tensors on the rank 0 process, None on the others

State vectors

class qtealeaves.emulator.StateVector(num_sites, local_dim=2, state=None, dtype=<class 'numpy.complex128'>)[source]

State vector class for handling small systems without the truncation of entanglement.

Arguments

num_sitesint

Number of sites in the system.

local_dimint, optional

Local dimension of the sites Default to 2.

stateNone or np.ndarray, optional

Pure state passed as numpy array. If None, the |0…0> state is initialized; otherwise, the state vector is initialized with the numpy array. Default to None.

dtypetype, optional

Initial data type if no numpy array is passed as initial state. The data type might change when executing operations. Default to np.complex128

add_update(other, factor_this=None, factor_other=None)[source]

Inplace addition as self = factor_this * self + factor_other * other. Exactly copied from the QteaTensor class (Feb 2024).

Arguments

othersame instance as self

Will be added to self. Unmodified on exit.

factor_thisscalar

Scalar weight for tensor self.

factor_otherscalar

Scalar weight for tensor other

apply_global_operator(global_op)[source]

Applies a global operator to the state; the state is updated in-place.

Arguments

global_opnumpy ndarray, rank-2

Global operator acting on the whole Hilbert space.

Returns

Return None; instance of class is updated in-place.

apply_two_site_operator(twosite_op, sites)[source]

Applies a two-site operator to the state; the state is updated in-place.

Arguments

twosite_opnp.array, rank-4

Two-site operator to apply. The contraction with the state is done over the links [2,3] of the operator.

siteslist/np.array of len 2

Sites indices on which to apply the operator.

Returns

Return None; instance of class is updated in-place.

dot(other)[source]

Calculate the dot-product or overlap between two state vectors, i.e., <self | other>.

Arguments

otherStateVector, numpy ndarray

Measure the overlap with this other state vector..

Returns

Scalar representing the overlap; complex valued.

classmethod from_groundstate(ham, num_sites, local_dim)[source]

Initialize the state vector with the ground state of a Hamiltonian passed as a matrix.

Arguments

hamnumpy ndarray, rank-2

Matrix of the system. Lower triangular part is sufficient since numpy.linalg.eigh is used.

num_sitesint

Number of sites in the system.

local_dimint

Local dimension of the sites

property global_dim

Global dimension property. Returns scalar with the dimension of the full Hilbert space.

property local_dim

Local dimension property. Returns the array of local dimensions.

meas_global_operator(global_op)[source]

Measure the expectation value of a global operator.

Arguments

global_opnumpy ndarray, rank-2

Global operator acting on the whole Hilbert space.

Returns

Return scalar value with the expectation value.

norm()[source]

Calculate the norm of the state.

Returns

normfloat

Real-valued scalar with the norm.

norm_sqrt()[source]

Calculate the square root of the norm of the state.

Returns

norm_sqrtfloat

The square root of the norm.

normalize()[source]

Normalize the current state in-place.

Returns

psiStateVector

Normalized version, same object as input (no copy)

property num_sites

Number of sites property.

reduced_rho(idx_keep)[source]

Calculate the reduced density matrix of a subset of sites.

Arguments

idx_keepint or list of ints

The site or sites specified here will be in the reduced density matrix.

Results

rho_ijknumpy ndarray, rank-2

Reduced density matrix for all the specified sites.

reduced_rho_i(ii)[source]

Calculate the reduced density matrix for a single site.

Arguments

iiint

Get reduced density matrix for this site.

Returns

rho_inumpy ndarray, rank-2

Reduced density matrix for site ii.

reduced_rho_ij(ii, jj)[source]

Calculate the reduced density matrix for a single site.

Arguments

iiint

Get reduced density matrix for this site and site jj.

jjint

Get reduced density matrix for this site and site ii.

Returns

rho_ijnumpy ndarray, rank-2

Reduced density matrix for site ii and jj.

property state

State property. The state vector in the shape of a N-legged tensor for N sites.

Tensor network nodes

class qtealeaves.emulator.TNnode(layer, index, children, link_idx)[source]

Class to encode a node in a tensor network, to work with arbitrary tensor network.

Parameters

layer: int

Layer of the network where the node lives

index: int

Index of the tensor inside the layer

children: list of TNnode

Children nodes

link_idx: int

Number for the new index for the links

add_parent(parent)[source]

Add the node parent as parent node of the class

Parameters

parentTNnode

New parent node

is_child(parent_node)[source]

Check if the class is the child of parent_node

Parameters

parent_nodeTNnode

Potential parent node

Returns

bool

True if parent_node is the parent

is_parent(child_node)[source]

Check if the class is the parent of child_node

Parameters

child_nodeTNnode

Potential child node

Returns

bool

True if child_node is the child

Abstract tensor networks

class qtealeaves.abstracttns.abstract_tn._AbstractTN(num_sites, convergence_parameters, local_dim=2, requires_singvals=False, tensor_backend=None)[source]

Abstract tensor network class with methods applicable to any tensor network.

Parameters

num_sites: int

Number of sites

convergence_parameters: TNConvergenceParameters

Class for handling convergence parameters. In particular, in the python TN simulator, we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular

values are neglected, i.e. if \(\lamda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)

local_dim: int, optional

Local dimension of the degrees of freedom. Default to 2.

requires_singvalsboolean, optional

Allows to enforce SVD to have singular values on each link available which might be useful for measurements, e.g., bond entropy (the alternative is traversing the whole TN again to get the bond entropy on each link with an SVD).

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

abstractmethod apply_local_kraus_channel(kraus_ops)[source]

Apply local Kraus channels to tensor network

Parameters

kraus_opsdict of QTeaTensor

Dictionary, keys are site indices and elements the corresponding 3-leg Kraus tensors

Returns

singvals_cut: float

Sum of singular values discarded due to truncation.

abstractmethod apply_projective_operator(site, selected_output=None, remove=False)[source]

Apply a projective operator to the site site, and give the measurement as output. You can also decide to select a given output for the measurement, if the probability is non-zero. Finally, you have the possibility of removing the site after the measurement.

Warning

Applying projective measurements/removing sites is ALWAYS dangerous. The information of the projective measurement should be in principle carried over the entire mps, by iteratively applying SVDs across all sites. However, this procedure is highly suboptimal, since it is not always necessary and will be processed by the following two-sites operators. Thus, the procedure IS NOT applied here. Take care that entanglement measures through TNObsBondEntropy may give incorrect results right after a projective operator application. Furthermore, if working with parallel approaches, projective operators should be treated with even more caution, since they CANNOT be applied in parallel.

Parameters

site: int

Index of the site you want to measure

selected_output: int, optional

If provided, the selected state is measured. Throw an error if the probability of the state is 0

remove: bool, optional

If True, the measured index is traced away after the measurement. Default to False.

Returns

meas_state: int

Measured state

state_probfloat

Probability of measuring the output state

static assert_extension(obj, extension)[source]

Asserts that obj.extension is equal to extension.

Parameters

objany

Will raise error if obj is not an instance of _AbstractTN

extensionstr

Will check if the extension of the TN ansatz matches the extionsion of the argument. If not, a type error is raised.

abstractmethod build_effective_operators(measurement_mode=False)[source]

Build the complete effective operator on each of the links. Now assumes self.eff_op is set.

check_obs_input(ops, idxs=None)[source]

Check if the observables are in the right format

Parameters

opslist of np.ndarray or np.ndarray

Observables to measure

idxs: list of ints, optional

If has len>0 we expect a list of operators, otherwise just one.

Return

None

checkpoint_copy_simulation_attr(src)[source]

Copy attributes linked to the simulation, like convergence parameters.

checkpoint_store(folder_name_output, dyn_checkpoint_file, int_str, checkpoint_indicator_file, is_dyn=False, jdic=None)[source]

Store the tensor network as checkpoint.

Arguments

folder_name_outputstr

Name of the output folder, where we store checkpoints.

dyn_checkpoint_filestr or None

Name of the previous checkpoint file, which can be deleted after creating the new checkpoint.

int_strstr

Identifier containing integers as string to identify the checkpoint when loading in a potential future run.

checkpoint_indicator_file: str

Path to file which indicates whether checkpoints exists.

is_dynbool, optional

Flag to indicate if checkpoint is for statics (False) or dynamics (True). Default to False.

jdicjson-compatible structure or None, optional

Store additional information as json. Default to None (store nothing).

clear_cache(num_qubits_keep=None, all_probs=None, current_key=None)[source]

Clear cache until cache size is below cache limit again. This function is empty and works for any tensor network without cache. If the inheriting tensor network has a cache, it has to be overwritten.

Arguments

all_probslist of dicts

Contains already calculated branches of probability tree. Each TTN has to decide if they need to be cleaned up as well.

clear_cache_rho()[source]

Clear cache of reduced density matrices.

property computational_device

Return the computational device stored in the tensor backend.

compute_energy(pos=None)[source]

Compute the energy of the TTN through the effective operator at position pos.

Parameters

poslist, optional

If a position is provided, the isometry is first shifted to that position and then the energy is computed. If None, the current isometry center is computed, by default None

Returns

float

Energy of the TTN

property convergence_parameters

Get the convergence settings from the TN.

convert(dtype, device)[source]

Convert the data type and device of a tensor network inplace.

copy(dtype=None, device=None)[source]

Make a copy of a TN.

Details

The following attributes have a special treatment and are not present in the copied object.

  • convergence_parameters

  • log file (filehandle)

  • MPI communicator

property data_mover

Get the data mover od the tensor.

debug_device_memory()[source]

Write informations about the memory usage in each device, and how many tensors are stored in each device. This should not be used in performance simulations but only in debugging.

abstract property default_iso_pos

Returns default isometry center position, e.g., for initialization of effective operators.

abstractmethod default_sweep_order(skip_exact_rgtensors=False)[source]

Default sweep order to be used in the ground state search/time evolution.

Arguments

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation. Usually set via the convergence parameters and then passed here. Default to False.

Returns

List[int] | List[Tuple[int]]

The generator that you can sweep through

default_sweep_order_back(skip_exact_rgtensors=False)[source]

Default sweep order backwards, e.g., for second-order methods.

property device

Device where the tensor is stored.

property dtype

Data type of the underlying arrays.

property dtype_eps

Data type’s machine precision of the underlying arrays.

dtype_from_char(dtype)[source]

Resolve data type from chars C, D, S, Z and optionally H.

dtype_to_char()[source]

Translate current data type of the tensor back to char C, D, S, Z, H, or I.

filter_sweep_order(sweep_order, skip_exact_rgtensors)[source]

Filter a sweep order with respect to exact rg tensors if flag active.

abstractmethod classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]

Decompose density matrix to tensor network of chosen type.

abstractmethod classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]

Converts LPTN to tensor network of chosen type.

abstractmethod classmethod from_mps(mps, conv_params=None, **kwargs)[source]

Converts MPS to tensor network of chosen type.

abstractmethod classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]

Decompose statevector to tensor network of chosen type.

abstractmethod classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]

Converts TTN to tensor network of chosen type.

abstractmethod classmethod from_tto(tto, conv_params=None, **kwargs)[source]

Converts TTO to tensor network of chosen type.

classmethod from_x(obj, conv_params=None, **kwargs)[source]

Converts tensor network of type x to chosen type.

Parameters

obj: _AbstractTN

object to convert to chosen type.

conv_params: TNConvergenceParameters, optional

Input for handling convergence parameters Default is None.

Return

new_obj: chosen type decomposition of obj.

If truncations are part of the underlying result, they are skipped.

Returns two sets of sites forming the bipartition of the system for a loopless tensor network. The link is specified via two positions in the tensor network.

Return a list of positions where all links are leading to. Number of entries is equal to number of links. Each entry contains the position as accessible in the actual tensor network.

Get the position of the partner tensor to use in the link expansion subroutine

Parameters

posint | Tuple[int]

Position w.r.t. which you want to compute the partner

Returns

int | Tuple[int]

Position of the partner

int

Link of pos pointing towards the partner

int

Link of the partner pointing towards pos

abstractmethod get_projector_function(pos, pos_links)[source]

Generates a function which locally projects out the effective projectors. Used in the excited state search.

Arguments pos : int | tuple[int]

The position of the tensor from which to project.

pos_linkslist[int] | list[tuple]

Position of neighboring tensors where the links in tensor lead to.

Returns Callable : the function.

abstractmethod get_rho_i(idx)[source]

Get the reduced density matrix of the site at index idx

Parameters

idxint

Index of the site

get_substate(first_site, last_site, truncate=False)[source]

Returns the smaller TN built of tensors from first_site to last_site, where sites refer to physical sites.

Parameters

first_siteint

First (physical) site defining a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

last_siteint

Last (physical) site of a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

truncateBool

If False, tensors are returned as is, possibly with non-dummy links on edge tensors. If True, the edges of will be truncated to dummy links. Default to False.

abstractmethod get_tensor_of_site(idx)[source]

Generic function to retrieve the tensor for a specific site. Compatible across different tensor network geometries.

Parameters

idxint

Return tensor containing the link of the local Hilbert space of the idx-th site.

property has_symmetry

Check if TN is built out of symmetric tensors.

is_dtype_complex()[source]

Check if data type is complex based on one example tensor..

property iso_center

Isometry center of the tensor network (int|tuple|None)

abstractmethod iso_towards(new_iso, keep_singvals=False, trunc=False, conv_params=None, move_to_memory_device=True)[source]

Shift the isometry center to the tensor at the corresponding position, i.e., move the isometry to a specific tensor, that might not be a physical.

Parameters

new_iso :

Position in the TN of the tensor which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

truncBoolean, optional

If True, the shifting is done via truncated SVD. If False, the shifting is done via QR. Default to False.

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD. If None, convergence parameters are taken from the TTN. Default to None.

move_to_memory_devicebool, optional

If True, when a mixed device is used, move the tensors that are not the isometry center back to the memory device. Default to True.

Details

The tensors used in the computation will always be moved on the computational device. For example, the isometry movement keeps the isometry center end the effective operators around the center (if present) always on the computational device. If move_to_memory_device is False, then all the tensors (effective operators) on the path from the old iso to the new iso will be kept in the computational device. This is very useful when you iterate some protocol between two tensors, or in general when two tensors are involved.

abstractmethod isometrize_all()[source]

Isometrize towards the default isometry position with no previous isometry center, e.g., works as well on random states.

Returns

None

abstractmethod kron(other)[source]

Concatenate two TN, taking the kronecker/outer product of the two states. The bond dimension assumed is the maximum between the two bond dimensions.

Parameters

other_AbstractTN

TN to concatenate with self.

Returns

_AbstractTN

Concatenation of the first TTN with the second in order

property local_dim

Local dimension property

Return information on local link (for symmetries more than integer).

static matrix_to_tensorlist(matrix, n_sites, dim, conv_params, tensor_backend=<qtealeaves.tensors.tensor_backend.TensorBackend object>)[source]

For a given matrix returns dense MPO form decomposing with SVDs

Parameters

matrixndarray

Matrix to write in LPTN(MPO) format

n_sitesint

Number of sites

dimint

Local Hilbert space dimension

conv_paramsTNConvergenceParameters

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) /\(\lambda_max\) <= \(\epsilon\) are truncated

tensor_backendinstance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

List[QteaTensor]

List of tensor, the MPO decomposition of the matrix

meas_local(op_list)[source]

Measure a local observable along all sites of the MPS

Parameters

op_listlist of _AbstractQteaTensor

local operator to measure on each site

Return

measuresndarray, shape (num_sites)

Measures of the local operator along each site

meas_magic(renyi_idx=2, num_samples=1000, return_probabilities=False, precision=14)[source]

Measure the magic of the state as defined in https://arxiv.org/pdf/2303.05536.pdf, with a given number of samples. To see how the procedure works see meas_unbiased_probabilities.

Parameters

renyi_idxint, optional

Index of the Rényi entropy you want to measure. If 1, measure the Von Neumann entropy. Default to 2.

num_samplesint | List[int], optional

Number of random number sampled for the unbiased probability measurement. If a List is passed, then the algorithm is run over several superiterations and each entry on num_samples is the number of samples of a superiteration. Default to 1000.

return_probabilitiesbool, optional

If True, return the probability dict. Default to False.

precision: int, optional

Precision for the probability interval computation. Default to 14. For precision>15 mpmath is used, so a slow-down is expected.

Returns

float

The magic of the state

meas_projective(nmeas=1024, qiskit_convention=False, seed=None, unitary_setup=None, do_return_probabilities=False)[source]

Perform projective measurements along the computational basis state

Parameters

nmeasint, optional

Number of projective measurements. Default to 1024.

qiskit_conventionbool, optional

If the sites during the measure are represented such that |201> has site 0 with value one (True, mimicks bits ordering) or with value 2 (False usually used in theoretical computations). Default to False.

seedint, optional

If provided it sets the numpy seed for the random number generation. Default to None

unitary_setupNone or UnitarySetupProjMeas, optional

If None, no local unitaries are applied during the projective measurements. Otherwise, the unitary_setup provides local unitaries to be applied before the projective measurement on each site. Default to None.

do_return_probabilitiesbool, optional

If False, only the measurements are returned. If True, two arguments are returned where the first are the measurements and the second are their probabilities. Default to False

Return

measuresdict

Dictionary where the keys are the states while the values the number of occurrences. The keys are separated by a comma if local_dim > 9.

meas_unbiased_probabilities(num_samples, qiskit_convention=False, bound_probabilities=None, do_return_samples=False, precision=15, mode='projection_z')[source]

Compute the probabilities of measuring a given state if its probability falls into the explored in num_samples values. The functions divide the probability space in small rectangles, draw num_samples random numbers and then follow the path until the end. The number of states in output is between 1 and num_samples.

For a different way of computing the probability tree see the function meas_even_probabilities() or meas_greedy_probabilities()

Parameters

num_samplesint

Maximum number of states that could be measured.

qiskit_conventionbool, optional

If the sites during the measure are represented such that |201> has site 0 with value one (True, mimics bits ordering) or with value 2 (False usually used in theoretical computations). Default to False.

probability_boundsdict, optional

Bounds on the probability computed previously with this function, i.e. if a uniform random number has value left_bound< value< right_bound then you measure the state. The dict structure is {‘state’ : (left_bound, right_bound)}. If provided, it speed up the computations since the function will skip values in the intervals already known. By default None.

do_return_samplesbool, optional

Enables, if True, to return the random number used for sampling in addition to the bound_probabilities. If False, only the bound_probabilities are returned. Default to False

precisionint, optional

Decimal place precision for the mpmath package. It is only used inside the function, and setted back to the original after the computations. Default to 15. If it is 15 or smaller, it just uses numpy.

modestr, optional

Mode of the unbiased sampling. Default is “projection_z”, equivalent to sampling the basis states on the Z direction. Possibilities: - “projection_z” - “magic”

Return

bound_probabilitiesdict

Dictionary analogous to the probability_bounds parameter. The keys are separated by a comma if local_dim > 9.

samplesnp.ndarray

Random numbers from sampling, only returned if activated by optional argument.

property memory_device

Return the memory device stored in the tensor backend.

ml_default_sweep_order(num_tensor_rule)[source]

Default sweep order for a machine learning optimization, where we potentially want to allow differences to the ground state sweep.

Arguments

num_tensor_rule: int

Specify if it is a one-tensor or two-tensor update.

Returns

sweep_orderList

List of tensor positions compatible with the corresponding ansatz. If not overwritten by ansatz, the default_sweep_order is returned.

ml_full_tn_step(num_grad_steps=1)[source]

Do a gradient descent backpropagation step on the whole TN.

Parameters

num_grad_stepsint

Number of steps as loop in the gradient descent.

Returns

lossfloat (as native data type of the backend on the CPU)

Value of the loss function.

abstractmethod ml_get_gradient_single_tensor(pos)[source]

Get the gradient w.r.t. to the tensor at pos similar to the two-tensor version.

Parameters

posint

Index of the tensor to work with.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

abstractmethod ml_get_gradient_two_tensors(pos, pos_p=None)[source]

Get the gradient w.r.t. the tensors at position pos, pos_p of the MPS following the procedure explained in https://arxiv.org/pdf/1605.05775.pdf for the data_sample given

Parameters

posint

Index of the tensor to optimize

pos_pint | None

Index of partner tensor. If None, partner tensor will be queried.

Returns

grad_AbstractQteaTensor

Gradient tensor

lossfloat

The loss function.

abstractmethod classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset)[source]

Generate an initial guess for a tensor network machine learning approach.

Arguments

convergence_parametersTNConvergenceParameters

Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.

tensor_backendTensorBackend

Selecting the tensor backend to run the simulations with.

initializestr

The string superposition-data will trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.

ml_data_mpoMLDataMPO

MPO of the labeled data set to be learned including the labels.

datasetList[MPS]

Data set represented as list of MPS states. Same order as in ml_data_mpo.

Returns

ansatz_AbstractTN

Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.

ml_one_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with one tensor and the label link in the environment.

Parameters

posint | tuple(int)

Position of the tensor to be optimized in the network.

num_grad_stepsint

Number of steps as loop in the gradient descent.

Returns

lossfloat (as native data type of the backend on the CPU)

Value of the loss function.

ml_optimize(ml_data_mpo, learning_rate, tn_ml_mode)[source]

Optimize the TN using the algorithm of Stoudenmire

Parameters

ml_data_mpopy:class:MLDataMPO

Feature dataset

learning_ratefloat or callable

Learning rate for the tensor update. If callable, it can depend on the sweep.

tn_ml_modestr

Defines the mode how to execute the machine learning. Must be compatible with the initial guess and the MPO, which will be checked. Available values are linkfree, linkfree_isofree, labellink, labellink_back, labelenv_back, and labelenv_back_isofree.

Previous arguments

  • num_sweeps: from convergence parameters max_iter Number of optimization sweeps (epochs)

  • no_impovement_criterion: from convergence parameters n_points_conv_check Exit criterion if consecutive iterations do not lead to an improvement, we exit.

  • decomposition_free_iso_towards : from tn_ml_mode Allow to skip QR/SVD decompositions when shifting isometry center. TN-ML does not require unitary gauged tensors if we have no label link and single-tensor updates.

  • use_backwards : from tn_ml_mode Use gradient descent with back propagation.

Returns

xp.ndarray

Singular values cut in the optimization

dict:

Simulation log as dictionary with entries loss_pre_sweep (list), loss_post_sweep (list), sweep_time (list), total_time (float).

Details

The machine learning modes are

  • linkfree : using overlap, mostly binary problems

  • linkfree_isofree : using overlap, single-site without decomposition, mostly binary problems.

  • labellink : standard TN-ML shifting label-link with the iso-center, gradient is calculated as tensor contraction.

  • labellink_back : standard TN-ML shiftling label-link with the iso-center, but using loss function, gradient descent, and back propagation.

Future methods are (but unittest fail here)

  • labelenv_back : label-link in environment, loss function minimized via gradient descent and back propagation.

  • labelenv_back_isofree : label-link in environment, loss function minimized via gradient descent and back propagation, no iso-shift.

  • labelenv_back_fulltn: optimize all tensors at the same time.

ml_optimize_single_tensor(pos, learning_rate, tracker={})[source]

Optimize a single tensors using a batch of data damples

Parameters

posint

Position of the tensor to optimize

learning_ratefloat

Learining rate for the tensor update

trackerdict, optional

Counts how often loss decreases and increases.

Returns

xp.ndarray

Singular values cut in the optimization

float

Value of the loss function

trackerdict

Counts how often loss decreases and increases.

ml_optimize_two_tensors(pos, learning_rate, direction=1, tracker={})[source]

Optimize two tensors using a batch of data damples

Parameters

posint

Position of the tensor to optimize

learning_ratefloat

Learining rate for the tensor update

directionint, optional

Direction either left to right (>0) or right to left (< 0). Default to 1.

trackerdict, optional

Counts how often loss decreases and increases.

Returns

xp.ndarray

Singular values cut in the optimization

float

Value of the loss function

trackerdict

Counts how often loss decreases and increases.

ml_predict(data_samples, n_jobs=1, do_round=True)[source]

Predict the labels of the data samples passed

Parameters

data_samplesList[py:class:MPS] | MLDataMPO

Feature dataset

true_labelsList[int]

Labels of the dataset

n_jobsint, optional

Number of parallel jobs for the optimization, by default 1

do_roundbool, optional

If true, labels will be rounded to integers, otherwise returned as float. Default to True

Returns

List | np.ndarray of rank 1

Predicted labels

ml_reorder_pos_pair(pos, pos_partner, link_pos, link_partner)[source]

By default, no re-ordering is done and arguments are returned as is.

Arguments

posint | tuple[int]

Position of the first tensor in the network.

pos_partnerint | tuple[int]

Position of the partner tensor in the network.

link_posint

Link in tensor connecting to partner tensor.

link_partnerint

Link in partner tensor connecting to tensor.

Returns

pos, pos_partner, link_pos, link_partner

Re-ordering of tensor and partner tensor if beneficial.

ml_to_id_step(pos, pos_p)[source]

Construct the id_step variables to shift effective operators given two positions in the tensor network.

Arguments

postuple[int] | int

First position in the _AbstractTN.

pos_ptuple[int] | int

Second position in the _AbstractTN.

Returns

id_step

Compatible step with ansatz

abstractmethod ml_two_tensor_step(pos, num_grad_steps=1)[source]

Do a gradient descent step via backpropagation with two tensors and the label link in the environment.

Parameters

posint | tuple(int)

Position of the tensor to be optimized in the network.

num_grad_stepsint

Number of steps as loop in the gradient descent.

Returns

lossfloat (as native data type of the backend on the CPU)

Value of the loss function.

move_pos(pos, device=None, stream=False)[source]

Move just the tensor in position pos with the effective operators insisting on links of pos on another device. Other objects like effective projectors will be moved as well. Acts in place.

Note: the implementation of the tensor backend can fallback to synchronous moves only depending on its implementation.

Parameters

posint | Tuple[int]

Integers identifying a tensor in a tensor network.

devicestr, optional

Device where you want to send the QteaTensor. If None, no conversion. Default to None.

streambool | stream | None, optional

If True, use a new stream for memory communication given by the data mover. If False, use synchronous communication with GPU. If not a boolean (and not None), we assume it is a stream object compatible with the backend. None is deprecated and equals to False. Default to False (Use null stream).

abstractmethod classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]

Broadcast a whole tensor network.

mpi_receive_tensor(from_)[source]

Receive the tensor from the process from_.

Parameters

from_int

Index of the process that sent the tensor

Returns

xp.ndarray

Received tensor

static mpi_sample_n_unique_states(state, num_unique, comm, tensor_backend, cache_size=None, cache_clearing_strategy=None, filter_func=None, mpi_final_op=None, root=0, **kwargs)[source]

Sample a target number of unique states. This is the target number of states, the actual number of states can differ.

Arguments

stateinstance of _AbstractTN

State to be sampled from; needs to exist only on root and will be broadcasted via MPI to all other threads.

num_uniqueint

Number of unique states to be sampled. This is a target number; the actual number of sampled states might differ in the end.

commMPI-communicator from mpi4py

Communicator of threads to be used for sampling.

tensor_backendTensorBackend

Tensor backend used for state, which will be needed to build up the state during bcast.

cache_sizeint, optional

Cache size limit for the sampling (bytes) per MPI-thread. Default to 1,000,000,000 (1GB).

cache_clearing_strategystr, optional

The strategy to be used to clear the cache within the sampling routine for TTN simulation. The possibilities are “num_qubits” or “state”. Default to “num_qubits”.

filter_funccallable or None, optional

Takes state string and probability boundaries as the two arguments in this order and returns True / False. Filtering can reduce the workload before MPI-communication of states. Default to `None (no filtering)

mpi_final_opstr or None

Either None or mpi_gather (root will contain all states) or mpi_all_gather (all threads will contain all states) Default to None.

rootint, optional

Thread-index of the MPI-thread holding the TN ansatz. Default to 0.

ansatz_AbstractTN (inside kwargs)

Ansatz is needed to broadcast the TN state to the other processes.

kwargskeyword arguments

Passed through to unbiased sampling, e.g., qiskit_convention, precision, and mode.

mpi_send_tensor(tensor, to_)[source]

Send the tensor in position tidx to the process to_.

Parameters

tensorxp.ndarray

Tensor to send

to_int

Index of the process where to send the tensor

Returns

None

abstractmethod norm()[source]

Calculate the norm of the state.

normalize()[source]

Normalize the state depending on its current norm.

property num_sites

Number of sites property.

Optimize a tensor pair via a space-link expansion.

Arguments

posint, tuple of ints (depending on TN)

position of tensor to be optimized

pos_partnerint, tuple of ints (depending on TN)

position of partner tensor, where link between tensor and partner tensor will be randomly expanded.

link_selfint

Link connecting to partner tensor (in tensor at pos)

link_partnerint

Link connecting to optimized tensors (in partner tensor).

requires_singvalsbool

Flag if calling methods upstream need singular values, i.e., want to replace QR with SVDs

Returns

float

Computed energy

optimize_single_tensor(pos)[source]

Optimize the tensor at position pos based on the effective operators loaded in the TTN

Parameters

poslist of ints or int

Position of the tensor in the TN

Returns

float

Computed energy

optimize_two_tensors(pos, pos_partner, link_self, link_partner)[source]

Local ground-state search on two tensors simultaneously.

Parameters

posTuple[int] | int

Position in the TN of the tensor to time-evolve

pos_partnerint, tuple of ints (depending on TN)

position of partner tensor, where link between tensor and partner tensor will be randomly expandend.

link_selfint

Link connecting to partner tensor (in tensor at pos)

link_partnerint

Link connecting to optimized tensors (in partner tensor).

Returns

float

Computed energy

permute_spo_for_two_tensors(spo_list, theta, link_partner)[source]

Returns permuted SPO list, permuted theta, and the inverse permutation.

pre_timeevo_checks(raise_error=False)[source]

Check if a TN ansatz is ready for time-evolution.

abstractmethod classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]

Construct a product (separable) state in a suitable tensor network form, given the local states of each of the sites.

randomize(noise=None, mpo_to_recalculate_eff_ops=None)[source]

Randomize all tensors in the tensor network. Removes eff_ops and eff_proj. If an mpo is passed as mpo_to_recalculate_eff_ops, the effective operators are recalculated with it.

Parameters

noisefloat | None

The amount of noise added. None randomizes completely.

reset_eff_ops_mpompo

Used to recalculate effective operator.

abstractmethod classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]

Read a TN from a formatted file.

classmethod read_pickle(filename, tensor_backend=None)[source]

Read via pickle-module.

filenamestr, path-like

Filename including path where to find the tensor network.

tensor_backendTensorBackend | None, optional

If not None, attribute _tensor_backend is set and data type and device are converted. Default to None (no conversion)

reinstall_isometry_parallel(*args, **kwargs)[source]

Reinstall the isometry in a parallel TN parallely

reinstall_isometry_serial(*args, **kwargs)[source]

Reinstall the isometry in a parallel TN serially

sample_n_unique_states(num_unique, exit_coverage=0.9999, ignore_opes_errors=False, **kwargs)[source]

Sample a given number of unique target states. This is the target number of states, the actual number of states can differ.

Arguments

num_uniqueint

Number of unique states to be sampled. This is a target number; the actual number of sampled states might differ in the end.

exit_coveragefloat, optional

Coverage at which sampling can stop even without reaching the target number of unique states. Default to 0.9999

ignore_opes_errorsbool, optional

Allows to ignore QTeaOpesError to return at least the samples that have been sampled so far. Default to False

kwargskeyword arguments

Passed through to unbiased sampling, e.g., qiskit_convention, precision, and mode. bound_probabilities is accepted if called from MPI sampling (identified by left-right keys).

Details

The target number of unique states will not be reached if the probability of the sampled states reaches the exit_coverage.

The target number of unique states will be overfulfilled in most other cases as the last superiteration might generate slightly more states than needed.

sanity_check()[source]

By default, we provide an empty sanity check method which can be overwritten by each class to check properties of the network.

save_pickle(filename)[source]

Save class via pickle-module. A state is always saved on a host CPU with tensor_backend.device set to “cpu”. After saving, the state and the tensor_backend are converted back to the original device.

Details

The following attributes have a special treatment and are not present in the copied object.

  • convergence_parameters

  • log file (filehandle)

  • MPI communicator

abstractmethod scale(factor)[source]

Multiply the tensor network state by a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network state.

abstractmethod scale_inverse(factor)[source]

Multiply the tensor network state by the inverse of a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network state.

set_cache_rho()[source]

Cache the reduced density matrices for faster access.

Update or set singvals on link via two positions.

abstractmethod site_canonize(idx, keep_singvals=False)[source]

Shift the isometry center to the tensor containing the corresponding site, i.e., move the isometry to a specific Hilbert space. This method can be implemented independent of the tensor network structure.

Parameters

idxint

Index of the physical site which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

property solver

Return current solver for the TN.

property tensor_backend

Return tensor backend stored for this TN-ansatz.

timestep(dt, mode, sweep_order=None, sweep_order_back=None)[source]

Evolve the Tensor network for one timestep.

Parameters

modeint

Currently encoded are single-tensor TDVP first order (1), two-tensor TDVP first order (2), two-tensor TDVP second order (3), and single-tensor TDVP second order (4). A flex-TDVP as (5) is pending. The “_kraus” extension for modes 1-4 includes dissipative evolution.

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

dtfloat

Timestep

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

Details

Flex-TDVP in the fortran implementation was using two-tensor updates as long as the maximal bond dimension is not reached and then a ratio of 9 single-tensor updates to 1 two-tensor update step.

timestep_mode_1(dt, sweep_order=None, normalize=False)[source]

Evolve the Tensor network for one timestep (single-tensor update 1st order).

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_1_kraus(dt, sweep_order=None, normalize=False)[source]

Evolve the Tensor network for one timestep of the Lindblad master equation (single-tensor update1st order) + Local dissipation.

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

convList[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_2(dt, sweep_order=None)[source]

Evolve the Tensor network for one timestep (two-tensor update 1st order).

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_2_kraus(dt, sweep_order=None)[source]

Evolve the Tensor network for one timestep of the Lindblad master equation (two-tensor update 1st order) + Local dissipation.

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

convList[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_3(dt, sweep_order=None, sweep_order_back=None)[source]

Evolve the Tensor network for one timestep (two-tensor update 2nd order).

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_3_kraus(dt, sweep_order=None, sweep_order_back=None)[source]

Evolve the Tensor network for one timestep of the Lindblad master equation (two-tensor update 2nd order) + Local dissipation.

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

convList[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_4(dt, sweep_order=None, sweep_order_back=None, normalize=False)[source]

Evolve the Tensor network for one timestep (single-tensor update 2nd order).

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_4_kraus(dt, sweep_order=None, sweep_order_back=None, normalize=False)[source]

Evolve the Tensor network for one timestep of the Lindblad master equation (single-tensor update 2nd order) + Local dissipation.

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

sweep_order_backList[int] | None

Order in which we iterate backwards through the network for the timestep. If None, use the default in self.default_sweep_order()[::-1]

Returns

convList[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_mode_5(dt, sweep_order=None, stride_two_tensor=10)[source]

Evolve the Tensor network for one timestep (mixed two-tensor and one-tensor update, first order).

Parameters

dtfloat

Timestep

sweep_orderList[int] | None

Order in which we iterate through the network for the timestep. If None, use the default in self.default_sweep_order()

stride_two_tensor: int

If maximum bond dimension is reached, do a two-tensor update every stride_two_tensor steps.

Returns

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_single_tensor(pos, next_pos, sc)[source]

Time step for a single-tensor update on a single tensor exp(sc*Heff*dt).

Parameters

posTuple[int] | int

Position in the TN of the tensor to time-evolve

next_pos: Tuple[int] | int

Position in the TN of the next tensor to time-evolve

sccomplex

Multiplicative factor in the exponent exp(sc*Heff*dt)

Return

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

Time step for a single-tensor update on two tensors exp(sc*Heff*dt).

Parameters

posTuple[int] | int

Position in the TN of the tensor to time-evolve

next_pos: Tuple[int] | int

Position in the TN of the next tensor to time-evolve

sccomplex

Multiplicative factor in the exponent exp(sc*Heff*dt)

Return

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

timestep_two_tensors(pos, next_pos, sc, skip_back)[source]

Time step for a single-tensor update on two tensors exp(sc*Heff*dt).

Parameters

posTuple[int] | int

Position in the TN of the tensor to time-evolve

next_pos: Tuple[int] | int

Position in the TN of the next tensor to time-evolve

sccomplex

Multiplicative factor in the exponent exp(sc*Heff*dt)

skip_backbool

Flag if backwards propagation of partner tensor can be skipped; used for last two tensors, partner tensor must be next position as well.

Return

List[qtealeaves.solvers.krylovexp_solver.KrylovInfo]

Information about the convergence of each Krylov update.

property tn_ml_mode

Returning the tensor network machine learning mode used in machine learning.

static tn_mpi_types()[source]

Provide convenient access to the TN_MPI_TYPES for TN ansaetze.

abstractmethod to_dense(true_copy=False)[source]

Convert into a TN with dense tensors (without symmetries).

abstractmethod to_statevector(qiskit_order=False, max_qubit_equivalent=20)[source]

Decompose a given TN into statevector form if pure.

Parameters

qiskit_orderbool, optional

If true, the order is right-to-left. Otherwise left-to-right (which is the usual order in physics). Default to False.

max_qubit_equivalentint, optional

Maximum number of qubits for which the statevector is computed. i.e. for a maximum hilbert space of 2**max_qubit_equivalent. Default to 20.

Returns

psiinstance of _AbstractQteaTensor

The statevector of the system

Raises

Mixed state: if mixed-state representations are not pure, an

error will be raised.

abstractmethod write(filename, cmplx=True)[source]

Write the TN in python format into a FORTRAN compatible format.

class qtealeaves.abstracttns._AbstractMatrixTN(num_sites, convergence_parameters, local_dim, requires_singvals, tensor_backend)[source]
Abstract class for tensor networks of the type:
| |
-o-o-o-
| |

It will be used for both the LPTN and the DenseMPO

Parameters

num_sitesint

Number of sites

convergence_parametersTNConvergenceParameters

Input for handling convergence parameters. In particular, in the LPTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) /\(\lambda_max\) <= \(\epsilon\) are truncated

local_dimint, optional

Dimension of Hilbert space of single site (defined as the same for each site). Default is 2

requires_singvalsboolean, optional

Allows to enforce SVD to have singular values on each link available which might be useful for measurements, e.g., bond entropy (the alternative is traversing the whole TN again to get the bond entropy on each link with an SVD).

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

apply_local_kraus_channel(kraus_ops)[source]

Apply local Kraus channels to tensor network

Parameters

kraus_opsdict of QTeaTensor

Dictionary, keys are site indices and elements the corresponding 3-leg kraus tensors

Returns

singvals_cut: float

Sum of singular values discarded due to truncation.

apply_mpo(mpo, top=False)[source]

Apply an _AbstractMatrixTN to the _AbstractMatrixTN on the sites sites. The MPO should have the following convention for the links: 0 is left link. 1 is physical link pointing downwards. 2 is phisical link pointing upwards. 3 is right link.

The sites are encoded inside the DenseMPO class.

Parameters

mpoDenseMPO

MPO to be applied

topbool, optional

Apply the MPO on the upper legs of the _AbstractMatrixTN. Default to False.

Returns

np.ndarray

Singular values cutted when the gate link is contracted

apply_one_site_operator(op, pos, top=False)[source]

Applies a one operator op to the site pos of the _AbstractMatrixTN.

Parameters

op: numpy array shape (local_dim, local_dim)

Matrix representation of the quantum gate

pos: int

Position of the qubit where to apply op.

top: bool, optional

If True, apply the two-site operator to the top of the tensor network instead of from the bottom, Default to False.

apply_two_site_operator(op, pos, swap=False, top=False)[source]

Applies a two-site operator op to the site pos, pos+1 of the _AbstractMatrixTN.

Parameters

op: numpy array shape (local_dim, local_dim, local_dim, local_dim)

Matrix representation of the quantum gate

pos: int or list of ints

Position of the qubit where to apply op. If a list is passed, the two sites should be adjacent. The first index is assumed to be the control, and the second the target. The swap argument is overwritten if a list is passed.

swap: bool, optional

If True swaps the operator. This means that instead of the first contraction in the following we get the second. Defalt to False

top: bool, optional

If True, apply the two-site operator to the top of the tensor network instead of from the bottom, Default to False.

Returns

singular_values_cutted: ndarray

Array of singular values cutted, normalized to the biggest singular value

Examples

swap=False  swap=True
  -P-M-       -P-M-
  2| |2       2| |2
  3| |4       4| |3
   GGG         GGG
  1| |2       2| |1
property current_max_bond_dim

Maximum bond dimension of the mps

property default_iso_pos

Returns default iso position to use in iso_towards

default_sweep_order(skip_exact_rgtensors=False)[source]

Default sweep order to be used in the ground state search/time evolution. Default for _AbstractMatrixTN is left-to-right.

Arguments

skip_exact_rgtensorsbool, optional

Allows to exclude tensors from the sweep which are at full bond dimension and represent just a unitary transformation. Usually set via the convergence parameters and then passed here. Default to False.

Returns

List[int]

The generator that you can sweep through

classmethod from_tensor_list(tensor_list, conv_params=None, iso_center=None, tensor_backend=None)[source]

Initialize the _AbstractMatrixTN tensors using a list of correctly shaped tensors

Parameters

tensor_listlist of ndarrays

List of tensors for initializing the _AbstractMatrixTN

conv_paramsTNConvergenceParameters, optional

Input for handling convergence parameters. In particular, in the _AbstractMatrixTN simulator we are interested in: - the maximum bond dimension (max_bond_dimension) - the cut ratio (cut_ratio) after which the singular values in SVD are neglected, all singular values such that \(\lambda\) / \(\lambda_max\) <= \(\epsilon\) are truncated

iso_centerNone or list of int, optional

Isometry center is between the two sites specified in a list. If the _AbstractMatrixTN has no isometry center, iso_center = None. Default is None

tensor_backendNone or instance of TensorBackend

Default for None is QteaTensor with np.complex128 on CPU.

Return

obj_AbstractMatrixTN

The _AbstractMatrixTN class composed of the given tensors


Returns two sets of sites forming the bipartition of the system for a loopless tensor network. The link is specified via two positions in the tensor network.

Arguments

pos_srctuple of two ints

Specifies the first tensor and source of the link.

pos_dsttuple of two ints

Specifies the second tensor and destination of the link.

Returns

sites_srclist of ints

Hilbert space indices when looking from the link towards source tensor and following the links therein.

sites_dstlist of ints

Hilbert space indices when looking from the link towards destination tensor and following the links therein.

Get the position of the partner tensor to use in the link expansion subroutine. It is the tensor towards the center, that is supposed to be more entangled w.r.t. the tensor towards the edge

Parameters

posint

Position w.r.t. which you want to compute the partner

Returns

int

Position of the partner

int

Link of pos pointing towards the partner

int

Link of the partner pointing towards pos

get_projector_function(pos, pos_links)[source]

Generates a function which locally projects out the effective projectors. Used in the excited state search.

get_substate(first_site, last_site, truncate=False)[source]

Returns the smaller TN built of tensors from first_site to last_site, where sites refer to physical sites.

Parameters

first_siteint

First (physical) site defining a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

last_siteint

Last (physical) site of a range of tensors which will compose the new TN. Python indexing assumed, i.e. counting starts from 0.

truncateBool

If False, tensors are returned as is, possibly with non-dummy links on edge tensors. If True, the edges of will be truncated to dummy links. Default to False.

get_tensor_of_site(idx)[source]

Generic function to retrieve the tensor for a specific site. Compatible across different tensor network geometries.

Parameters

idxint

Return tensor containin the link of the local Hilbert space of the idx-th site.

install_gauge_center()[source]

Install a gauge center to the rightmost site of the _AbstractMatrixTN.

Returns

None

property iso_center

Scalar isometry center

iso_towards(new_iso, keep_singvals=False, trunc=False, conv_params=None, move_to_memory_device=None, normalize=False)[source]

Shift the isometry center to the tensor

isometrize_all()[source]

Isometrize towards the default isometry center with no assumption of previous isometry center, e.g., works as well on random states.

Returns

None

kron(other)[source]

Concatenate _AbstractMatrixTN tensors with other _AbstractMatrixTN’s tensors. The function doesn’t renormalize tensor network.

Parameters

other_AbstractMatrixTN

_AbstractMatrixTN to concatenate

Return

_AbstractMatrixTN

kronecker product of the two _AbstractMatrixTN’s

scale(factor)[source]

Multiply the tensor network by a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network.

scale_inverse(factor)[source]

Multiply the tensor network by a scalar factor.

Parameters

factorfloat

Factor for multiplication of current tensor network.

site_canonize(idx, keep_singvals=False, normalize=False)[source]

Shift the isometry center to the tensor containing the corresponding site, i.e., move the isometry to a specific Hilbert space. This method can be implemented independent of the tensor network structure.

Parameters

idxint

Index of the physical site which should be isometrized.

keep_singvalsbool, optional

If True, keep the singular values even if shifting the iso with a QR decomposition. Default to False.

swap_qubits(sites, conv_params=None, trunc=True)[source]

This function applies a swap gate to sites, i.e. swaps these two qubits

Parameters

sitesTuple[int]

The qubits on site sites[0] and sites[1] are swapped

conv_paramsTNConvergenceParameters, optional

Convergence parameters to use for the SVD in the procedure. If None, convergence parameters are taken from the TTN. Default to None.

Return

np.ndarray

Singualr values cut in the process of shifting the isometry center. None if moved through the QR.

to_matrix(qiskit_order=False, max_qubit_equivalent=10)[source]

Return the tensor list representation of the _AbstractMatrixTN.

Arguments

qiskit_order: bool, optional

weather to use qiskit ordering or the theoretical one. For example the state |011> has 0 in the first position for the theoretical ordering, while for qiskit ordering it is on the last position.

max_qubit_equivalent: int, optional

Maximum number of qubit-equivalents the matrix can have and still be transformed into a matrix. If the number of qubit-equivalents is greater, it will throw an exception. Default to 10.

Return

QteaTensor

Tensor representation of the _AbstractMatrixTN with rank-2 tensor without symmetries and rank-3 tensor with symmetries.

class qtealeaves.abstracttns.postprocess_statedict(state_dict, local_dim=2, qiskit_convention=False)[source]

Remove commas from the states defined as keys of statedict and, if qiskit_convention=True invert the order of the digits following the qiskit convention

Parameters

state_dictdict

State dictionary, which keys should be of the format ‘d,d,d,d,d,…,d’ with d from 0 to local dimension

local_dimint or array-like of ints, optional

Local dimension of the sites. Default to 2

qiskit_conventionbool, optional

If True, invert the digit ordering to follow qiskit convention

Return

dict

The postprocessed state dictionary

Setup unitaries before projective measurements

class qtealeaves.emulator.UnitarySetupProjMeas(unitaries, mode='R')[source]

Setup for applying unitaries prior to a projective measurement via meas_projective.

Parameters

unitarieslist of xp.ndarrays of rank-2

List of unitaries, which will be applied to the local Hilbert space according to the mode.

modechar

Mode R, we draw randomly unitaries from the list and apply them before the projective measurement. Mode S select the unitary at the corresponding site, i.e., the i-th site applies always the i-th unitary.

get_unitary(site_idx)[source]

Retrieve the unitary for a site.

Parameters

site_idxint

Get unitary for this site. Although it has to be passed always, it is only evaluated in mode=S.

Returns

unitarynp.ndarray of rank-2

Tensor to be applied as local unitary to the site.